πŸ› οΈ

Redux-toolkit

Full Example Code (store )
import * as jose from 'jose' import { configureStore, createSlice } from "@reduxjs/toolkit"; // create slice want three params name , initial value and reducer function const initialState = { id: "", name: "", mobile: "", createdAt: "", email: "",login:false ,role:"user"}; const token=localStorage.getItem('token'); if (token) { // This is the whole object which is being converted to jwt const decodedJwt = jose.decodeJwt(token) // console.log(decodedJwt) const userDataRecieve = decodedJwt.data; initialState.name = userDataRecieve.name; initialState.login = true; initialState.createdAt=userDataRecieve.createdAt; initialState.id=userDataRecieve.id; initialState.mobile=userDataRecieve.mobile; initialState.email=userDataRecieve.email; initialState.role=userDataRecieve.role; if (!decodedJwt) { localStorage.removeItem(token); } } const userData = createSlice({ name: "users", initialState, reducers:{ setid: (state, action) => void(state.id = action.payload), setname: (state, action) => void(state.name = action.payload), setmobile: (state, action) => void(state.mobile = action.payload), setcreatedAt: (state, action) => void(state.createdAt = action.payload), setemail: (state, action) => void(state.email = action.payload), setrole: (state, action) => void(state.role = action.payload), setlogin: (state, action) => void (state.login = action.payload) } }); const store = configureStore({reducer:{users:userData.reducer}}); // export default userData.actions; // export const actions = userData.actions; export const { setid, setname, setmobile, setcreatedAt, setemail, setlogin,setrole } = userData.actions; export default store; // export default {store,action:userData.actions};
App.js ( Provider tag to provide data throughout the applicatio)
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import 'flowbite'; import 'flowbite-react'; import { Provider } from 'react-redux'; import { BrowserRouter as Router } from 'react-router-dom'; import store from './store/userStore'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Router > <Provider store={store}> <App /> </Provider> </Router> ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
To get and update data

To get data { useSelector } function | to update data {useDispatch}

import { useSelector, useDispatch } from 'react-redux/es/exports'; //all reducers for updating the value import { setname , setemail, setid, setlogin, setmobile, setrole } from '../../store/userStore'; // inside the function component const dispatch = useDispatch(); // ========== to get name from a slice ============ const name = useSelector((store) => store.users.name); // =========== to update the value ================= dispatch(setlogin(true)); dispatch(setname(userDataRecieve.name)); dispatch(setid(userDataRecieve.id)); dispatch(setemail(userDataRecieve.email)); dispatch(setmobile(userDataRecieve.mobile)); dispatch(setrole(userDataRecieve.role));
Β 

πŸ”₯
Redux toolkit ka tab use karte hai jab hamare pass multiple states hoti hai maintain karne k liye or hme baar baar alag alalg action type define karna padta hai jo ki practical case mai possible nahi hai kyuki hamare pass bahut saari states hogi
Then we will use redux-toolkit to solve this problem
To install run the following command
npm install @reduxjs/toolkit
Ab suppose hme diffrent slices maintain karne ho like use ka data , votes ka data and some other data set then we can split them into slices and use easily
notion image
we have to import the createSlice from the library redux toolkit
notion image
har slice k liye hme alag name initialstate or reducerFunctions define karne hoge( we can also have multiple reducers for one slice)
notion image
now we don’t need to write all other stated as it is when we are updating in the reducer function/
πŸ”₯
ab yaha par hum kaam whi kar rhe hai bus hmne reducer function ki jagah slice_name.reducer pass kar diya in the createStore function but jab hamare pass ek se jyada reducer functions hoge for diffrent diffrent slices then we have to use createConfig
notion image
now ye reducer is the combine reducerFunction of the voteSlice.reducer and in the same way other reducers as well
Β 

Dispatching the value from component( updating data )

Now if we have to update some value of voteSlice then we have to first export the action from the current store file ( vote-store.js)
notion image
Now we have multiple slices hum ise as an object bhej sakte hai aur yaha par hme .actions hi use karna hai to trigger some action from the component
Β 

In the component ( Votes.js ) β‡’

To update the actions we have to import the actions which we are exporting from store
notion image
Now we have to trigger some action from the Handlers
Β 
What we have previously use
notion image
What is given by toolkit
notion image
πŸ”₯
Now yaha par hum direct actions.Increment( ) likh rhe hai kyuki actions = voteSlice.actions hai jo ki reducer ki Increment property ko access kar rha hai or jo ki ek function hai Jo ek purticular state ko update kar rha hai :: For refrence check the below toggle
reducer
notion image
notion image
πŸ”₯
One more Important point here is that agar hum dynamically kisi value ki increase ya decrease karna chahte hai to pehle hum value ka use karte the but yaha by default redux toolkit use payload prop mai bhejta hai jise hum reducer mai handle kar skte hai
Β 

How to access the payload from the component( In reducer )

by default all the values are availble as payloads in the reducer
notion image
Β