How to reset the state of a Redux store?

前端 未结 30 2490
陌清茗
陌清茗 2020-11-22 06:20

I am using Redux for state management.
How do I reset the store to its initial state?

For example, let’s say I have two user accounts (u1 and

30条回答
  •  借酒劲吻你
    2020-11-22 06:29

    I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.

    User record action

    export const clearUserRecord = () => ({
      type: CLEAR_USER_RECORD
    });
    

    Logout action creator

    export const logoutUser = () => {
      return dispatch => {
        dispatch(requestLogout())
        dispatch(receiveLogout())
        localStorage.removeItem('auth_token')
        dispatch({ type: 'CLEAR_USER_RECORD' })
      }
    };
    

    Reducer

    const userRecords = (state = {isFetching: false,
      userRecord: [], message: ''}, action) => {
      switch (action.type) {
        case REQUEST_USER_RECORD:
        return { ...state,
          isFetching: true}
        case RECEIVE_USER_RECORD:
        return { ...state,
          isFetching: false,
          userRecord: action.user_record}
        case USER_RECORD_ERROR:
        return { ...state,
          isFetching: false,
          message: action.message}
        case CLEAR_USER_RECORD:
        return {...state,
          isFetching: false,
          message: '',
          userRecord: []}
        default:
          return state
      }
    };
    

    I am not sure if this is optimal?

提交回复
热议问题