简体   繁体   中英

How can I put my initial state into my redux store?

I am trying to make a login functionality with redux. The problem is I can not figure out how to work with my initial state where I stored my userInfo.

import { configureStore } from '@reduxjs/toolkit'
import { postListReducer, postDetailsReducer } from './reducers/postReducers'
import { userLoginReducer } from './reducers/userReducers'

const store = configureStore({
  reducer: {
    postList : postListReducer,
    postDetails : postDetailsReducer,
    userLogin : userLoginReducer,
  },
})

const userInfoFromStorage = localStorage.getItem('userInfo') ?
  JSON.parse(localStorage.getItem('userInfo')) : null

const initialState = {
    userLogin : {userInfo: userInfoFromStorage}
  }
  

export default store

I can see that you are using redux toolkit, you might add initial state in userLoginReducer file, there is a prop there for you. As for the overral solution i would suggest you to take a look at this repo: https://github.com/rt2zz/redux-persist

Maybe this library is what you are looking for.

Source: https://redux-toolkit.js.org/api/createslice#initialstate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM