简体   繁体   中英

how to store redux state

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?

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);

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