Redux

folder Projet: test_react_project

Redux est un module qui permet de gérer les states de chaque components dans une seule state Globale

Redux se compose de:
  1. Store: :créer une seule State regroupant les state de toutes les components
  2. Reducer :un objet contenant:
    1. le State locale d'une component
    2. Les fonctions (Actions) qui manipule le state locale

Installation: Redux

npm install @reduxjs/toolkit react-redux

Exemple1

reducers/PostReducer.js
import { createSlice } from '@reduxjs/toolkit'

//la valeur initiale de l'objet state.post
const initialState = {  name:'post content',  likes:0}
//le reducer contenant des fonctions slice permettant de
export const PostReducer = createSlice({
    name: 'post',
    initialState,
    reducers: {
        //Action1
      like: (state) => {
        state.likes+=1
      },
     //Action2
      dislike: (state) => {
        state.likes-=1
      },
      changerName: (state, action) => {
        state.name=action.payload  //récupérer la valeur envoyer par le distapcher
      },
    },
})

// Action creators are generated for each case reducer function
export const { like,dislike,changerName } = PostReducer.actions

export default PostReducer.reducer

Store/store.js
import { configureStore } from '@reduxjs/toolkit'
import PostReducer from '../reducers/PostReducer'

//store contient la State Globale de l'application
export const store = configureStore({
  reducer: {
    //nom de l'objet du state (state.post):le reducer qui traite cet variable
    post:PostReducer
   
  },
})
Components/PostComponent.js
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {like} from '../reducers/PostReducer'
export default function PostComponent()
{
    //appler le state post du store
    const post=useSelector((state)=>state.post)

    const dispatch=useDispatch();
    const likeMe=()=>{
      dispatch(like())
    }

    return (
        <div>
          Le nom :{post.name} <br/>
          Nbre likes:{post.likes}
          <button onClick={likeMe} >Like</button>    
        </div>
    )
}
Components/TestComponent.js
import React, { useState } from "react"
import { useDispatch,useSelector } from "react-redux"
import {changerName} from '../reducers/PostReducer'
export default function TestComponent()

{
    //récupéer la valeur actuelle de l'attribut name de la variable du state post
    const post=useSelector((state)=>state.post)
    //on peut créer des variables de state mais ne sont pas ajouté dans le Store
    const [name,setName]=useState(post.name)

    const dispatch=useDispatch();
    const changerPostName=(e)=>{
        dispatch(changerName(e.target.value))
        }
    return   (
        <div>
            <input type="text"  defaultValue={name} onChange={changerPostName}/>
        </div>
    )
}
App.js
import logo from './logo.svg';
import './App.css';
import PostComponent from './components/PostComponent';
import TestComponent from './components/TestComponent';


function App() {
  return (
    <div className="App">
     
    <PostComponent />
    <TestComponent />
     
    </div>
  );
}

export default App;

index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store } from './store/store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
 <App />
  </Provider>,
  document.getElementById('root')
)