I am beginner using Redux,I want to store redux's state in my app , because whenever I refresh the page redux will reset the state . this is my the userSlice.js:
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
userName: null,
userEmail: null
}
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
setActiveUser: (state, action) => {
state.userName = action.payload.userName
state.userEmail = action.payload.userEmail
},
setUserLogOutState: state => {
state.userName = null
state.userEmail = null
}
}
});
export const { setActiveUser, setUserLogOutState } = userSlice.actions
export const selectUserName = state => state.user.userName
export const selectUserEmail = state => state.user.userEmail
export default userSlice.reducer
store.js
import { configureStore } from '@reduxjs/toolkit'
import userReducer from './userSlice'
export default configureStore({
reducer: {
user: userReducer
}
})
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
Signup.js
const dispatch = useDispatch()
const userName = useSelector(selectUserName)
const userEmail = useSelector(selectUserEmail)
const onClickButton = (e) => {
e.preventDefault();
signInWithGoogle().then((result) => {
dispatch(setActiveUser({
name: result.user.displayName,
email: result.user.email
}))
})
}
So how exactly can i store the state of the user whenever i refresh the page ?
CodePudding user response:
There are some ways. One that comes to my mind is using localStorage. That way you can do something like:
userSlice.js:
const savedState = localStorage.getItem('previousState');
const initialState = savedState ? savedState : {
userName: null,
userEmail: null
}
And then it would be initialized if the previous state was saved. All you would need to do is update your localStorage state whenever you update your redux state.
localStorage.setItem('previousState', newReduxState);