How to reset the state of a Redux store?

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

    Define an action:

    const RESET_ACTION = {
      type: "RESET"
    }
    

    Then in each of your reducers assuming you are using switch or if-else for handling multiple actions through each reducer. I am going to take the case for a switch.

    const INITIAL_STATE = {
      loggedIn: true
    }
    
    const randomReducer = (state=INITIAL_STATE, action) {
      switch(action.type) {
        case 'SOME_ACTION_TYPE':
    
           //do something with it
    
        case "RESET":
    
          return INITIAL_STATE; //Always return the initial state
    
       default: 
          return state; 
      }
    }
    

    This way whenever you call RESET action, you reducer will update the store with default state.

    Now, for logout you can handle the like below:

    const logoutHandler = () => {
        store.dispatch(RESET_ACTION)
        // Also the custom logic like for the rest of the logout handler
    }
    

    Every time a userlogs in, without a browser refresh. Store will always be at default.

    store.dispatch(RESET_ACTION) just elaborates the idea. You will most likely have an action creator for the purpose. A much better way will be that you have a LOGOUT_ACTION.

    Once you dispatch this LOGOUT_ACTION. A custom middleware can then intercept this action, either with Redux-Saga or Redux-Thunk. Both ways however, you can dispatch another action 'RESET'. This way store logout and reset will happen synchronously and your store will ready for another user login.

提交回复
热议问题