Redux-Toolkit/Persist

lucky_shrivas

Lucky Shrivas

Posted on August 9, 2024

Redux-Toolkit/Persist

Redux-toolkit/persist

  1. Store/Store.config.js
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import persistReducer from "redux-persist/es/persistReducer";
import persistStore from "redux-persist/es/persistStore";
import storage from "redux-persist/lib/storage";

import userSlice from "./slices/user.Slice.js";


const persistConfig = {
  key: "user",
  storage,
  blacklist: [],
};


const rootReducer = combineReducers({
  user: userSlice,
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
});

export const persistor = persistStore(store);
Enter fullscreen mode Exit fullscreen mode
  1. Index.jsx
import React from 'react'
import { Provider } from "react-redux";

function index() {
  return (
    <>
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
      <app/>
      </PersistGate> 
     </Provider>
    </>
  )
}

export default index
Enter fullscreen mode Exit fullscreen mode
  1. Store/Slices/user.Slice.js
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";


export const GetAllUser = createAsyncThunk(
  "GetAllUser",
  async (payload, { rejectWithValue }) => {
    try {
      const response = await axios.get(`localhost:8000/api/get-all-user`);
      return response.data;
    } catch (error) {
      return rejectWithValue(
        error.response.data.message || "failed"
      );
    }
  }
);



const storeSlice = createSlice({
  name: "store",
  initialState: {
   userData:null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      // Initialize builder
      .addCase(GetAllUser.pending, (state) => {
        state.loading = true;
        state.error = false;
      })
      .addCase(GetAllUser.fulfilled, (state, action) => {
        state.loading = false;        
        state.userData = action.payload.user;
      })
      .addCase(GetAllUser.rejected, (state, action) => {
        state.loading = false;
        state.userData = null;
      })
    }
  })

export default storeSlice.reducer;
Enter fullscreen mode Exit fullscreen mode
  1. App.jsx
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import {GetAllUser} from './Store/Slices/user.Slice.js'

function App() {
  const dispatch = useDispatch();
  const userData = useSelector((state) => state.user.userData);
useEffect(()=>{
  dispatch(GetAllUser)
},[])

  return (
    <div>
      <pre>userData</pre>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
lucky_shrivas
Lucky Shrivas

Posted on August 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related