rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.97k stars 867 forks source link

failed to preserved initial state value at rehydrate #1451

Open vishal590 opened 1 year ago

vishal590 commented 1 year ago

got 10000000 at init and at persist but at rehydrate got 0

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  name: "",
  address: "",
  balance: 10000000,
  isLogin: localStorage.getItem("token") ? true : false,
};

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    setUser: (state, action) => {
      return {
        ...state,
        ...action.payload,
      };
    },
    updateBalance: (state, action) => {
      return {
        ...state,
        balance: action.payload,
      };
    },
    updateAddress: (state, action) => {
      return {
        ...state,
        address: action.payload,
      };
    },
    updateName: (state, action) => {
      return {
        ...state,
        name: action.payload,
      };
    },
    logIn: (state, action) => {
      localStorage.setItem("token", action.payload);
      return {
        ...state,
        isLogin: true,
      };
    },
    logOut: (state) => {
      state.name = "";
      state.address = "";
      state.balance = 0;
      state.isLogin = false;
      localStorage.removeItem("token");
    },
  },
});

export const { setUser, updateName, updateBalance, updateAddress, logIn, logOut } =
  userSlice.actions;
export const getUser = (state) => state.user;
export default userSlice.reducer;