0% found this document useful (0 votes)
25 views3 pages

TodoApp Using Redux

Uploaded by

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

TodoApp Using Redux

Uploaded by

jamrimaryem9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

TodoApp Using Redux

Redux => biblio Javascript permet de centraliser l’état dans un seul store, pour éviter les problèmes
de props drilling

Vocabulaire redux :

• Store
• Provider import {Provider } from ‘react-redux’
• Selector useSelector
• Reducer
• Actions {type : typeValue,payload :payloadValue}
• Dipatcher useDispatch

Outils : pour exploiter la bibliothèque redux , on doit installer redux et react-redux

Exemple Pratique : TodoList app user react redux

1. –npx create-react-app .
-- npm i redux react-redux
2. Create store (store.js) : utiliser la fonction createStore : import {createStore} from ‘redux ‘
Import {todoReducer} from ‘todoReducer.js’
Export default const store=createStore(todoReducer)
todoReducer => reducer (function qui prend ne parameter state et action et retourne
nouvelle version du state)
3. todoReducer.js =>
const initialState={todos :[]}
export const todoReducer=(state=initialState,action){
switch(action.type){

case ‘ADD’ :
return {…state,todos:[…state.todos,action.payload]}
case ‘DELETE’ :
return {…state,todos:state.todos.filter((todo,pos)=>
todo.id!==action.payload.id)}
case ‘UPDATE’ :
return {…state,todos: state.todos.map((todo,pos)=>
todo.id===action.payload.id?action.payload:todo)}

Default : return state;

}
4. App.js
Import {Provider} from ‘react-redux’
Import TodoStore from ‘store.js’
Import TodoApp from ‘TodoApp.js’
2

Return (
<Provider store={TodoStore}>
< TodoApp/>
</Provider>

}
5. TodoApp.js

Import {useSelector,useDispatch] from ‘react-redux’


Import {v4 as uuid} from ‘uuid’
Const todos=useSelector(state=>state.todos)
Const dispatcher= useDispatch()
Const[task,setTask ]=useState(“”);

Const handelAdd=()=>{
Let newTask={id:uuid(),task,done:false}
Dispatcher({type:’ ADD’,payload:newTask})

Const handelEdit=(id)=>{
Dispatcher({type:’ DELETE,payload:id})

Return(

<>
<div>
<input type=”text” value={task} onChange={(e)=>setTask(e.target.value)}/>
<button onClick={handelAdd}>Add To Do</button>
</div>
<div>
{

Todos &&(
<ul>
{
Todos.map((todo,pos)=>(

<li> {todo.task} <button onClick={handelDelete(todo.id)}>Delete</button>


3

<button onClick={handelEdit(todo)}>Edit</button></li>

)) ;

}
</ul>

</div>

</>

You might also like