the scenario is when the user log in, i store his userInfo in localstorage, to avoid losing the session when i refresh the page, this is my previous code in Store.js with react-redux
// import
const reducer = combineReducers({
userLogin: userLoginReducer,
userRegister: userRegisterReducer,
// more reducers
})
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: null
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
}
const middleware = [thunk]
const store = createStore(
reducer,
initialState, // i used to pass initial state (with userInfo in it) whith createStore
composeWithDevTools(applyMiddleware(...middleware))
)
export default store
this code used to work well for me, when i refresh the page i don't lose my session
and now i'm trying to migrate to redux-toolkit (i'll not change my old reducers, i"ll use the new way of code using createSlice with new ones only)
// import
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: null
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
}
const store = configureStore({
reducer: {
userLogin: userLoginReducer,
userRegister: userRegisterReducer,
userDetails: userDetailsReducer,
// more reducers
},
initialState, // i don't know if this way is correct to add initial state to configureStore, it doesn't work
})
export default store
configureStore works well in my app with all reducers
- except the fact that i can't pass userInfo from localstorage to the initialState of userLogin to keep it populated to avoid losing the session when i refresh the page (NB: in my components i check if there's any data in userLogin ? if true nothing happens : if false user is sent to Login page