How to reset the state of a Redux store?

前端 未结 30 1922
陌清茗
陌清茗 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:37

    The following solution works for me.

    First on initiation of our application the reducer state is fresh and new with default InitialState.

    We have to add an action that calls on APP inital load to persists default state.

    While logging out of the application we can simple reAssign the default state and reducer will work just as new.

    Main APP Container

      componentDidMount() {   
        this.props.persistReducerState();
      }
    

    Main APP Reducer

    const appReducer = combineReducers({
      user: userStatusReducer,     
      analysis: analysisReducer,
      incentives: incentivesReducer
    });
    
    let defaultState = null;
    export default (state, action) => {
      switch (action.type) {
        case appActions.ON_APP_LOAD:
          defaultState = defaultState || state;
          break;
        case userLoginActions.USER_LOGOUT:
          state = defaultState;
          return state;
        default:
          break;
      }
      return appReducer(state, action);
    };
    

    On Logout calling action for resetting state

    function* logoutUser(action) {
      try {
        const response = yield call(UserLoginService.logout);
        yield put(LoginActions.logoutSuccess());
      } catch (error) {
        toast.error(error.message, {
          position: toast.POSITION.TOP_RIGHT
        });
      }
    }
    

    Hope this solves your problem!

提交回复
热议问题