0% found this document useful (0 votes)
40 views

Use Reducer

This React component uses the useReducer hook to manage state in a todo list application. It defines an initial state and reducer function to handle different actions like adding, deleting, and editing tasks. The component renders the todo list and includes an input, add button, and edit/delete buttons for each task that call methods tied to dispatching actions.

Uploaded by

Khalid Yn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Use Reducer

This React component uses the useReducer hook to manage state in a todo list application. It defines an initial state and reducer function to handle different actions like adding, deleting, and editing tasks. The component renders the todo list and includes an input, add button, and edit/delete buttons for each task that call methods tied to dispatching actions.

Uploaded by

Khalid Yn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import React,{useReducer} from "react";

const initialState=()=>{
tasks:[];
newTask:"";
}
const reducer=(state,action){
switch(action.type){
case "add":
return{
...state,tasks:[...state.tasks,action.payload];
}
case "delete":
return{
...state,tasks:state.tasks.filter((element,i)=>i !== action payload);
}
case "edit":
const UpdateTasks=[...tasks];
UpdateTasks[action.payload.index]=[action.payload.value];
return{
...state,tasks:UpdateTasks;
}
case "SetNewTask":
return{
...state,newTask:action.payload;
}
default:
return state;
}
}
export default function TodoList( ){
const[state,dispatch]=useReducer(reducer,initialState);
const HandleAdd=( )=>{
dispatch({type:"add",payload:newTask});
dispatch({type:"SetNewTask",payload:""});
}
const HandleDelete=(index)=>{
dispatch({type:"delete",payload:index});
}
const HandleEdit=(index)=>{
const UpdateValue=prompt("Mise a jour du texte:");
dispatch({type:"edit",payload:{index,value:UpdateValue}});
}
return(
<div>
<h1>Todo List</h1>
<input type="text" value={state.newTask}
onChange={(e)=>dispatch({type:"setNewTask" payload:e.target.value})}/>
<button onclick={HandleAdd}>Add</button>
state.tasks.map((task,cle)=>(
<ul>
<li>{task}</li>
<li>
<button onClick={()=>HandleEdit(index)}>Delete</button>
<button onclick={HandleEdit(index)}>Edit</button>
</li>
</ul>
)
</div>
);
}
}

You might also like