0

How to reset a specific Redux Reducer to initial state
Is it possible to reset it to initial state?
I want when leave the register page, like go to Home or other pages the state of the register reducer back to initial state in React Native...

const initialState = {
  registerLoading: false,
  registerResult: null,
  registerError: null,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case REGISTER_USER_ACTION:
      return {
        ...state,
        registerLoading: action.payload.loading,
        registerResult: action.payload.data,
        registerError: action.payload.errorMessage,
      };    
     default:
        return state;
  }
}
Miraii App2
  • 35
  • 1
  • 5
  • You can simply return the initial state when the relevant action occurs. – trixn Aug 04 '21 at 14:14
  • If you respected the rule of not mutating the state but always replacing it with an updated version, of course you can: you simply need to `return { ...initialState }` when the desired action occurs. – secan Aug 04 '21 at 14:19
  • For redux toolkit, See answer here: https://stackoverflow.com/a/73372455/10030693 – Gilbert Aug 16 '22 at 10:24

1 Answers1

0

You should be able to dispatch an action when you leave the page, e.g. action.type = RESET_INITIAL_STATE.

Create the case in your switch statement for it:

const initialState = {
  registerLoading: false,
  registerResult: null,
  registerError: null,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case REGISTER_USER_ACTION:
      return {
        ...state,
        registerLoading: action.payload.loading,
        registerResult: action.payload.data,
        registerError: action.payload.errorMessage,
      }; 
    case RESET_INITIAL_STATE:
      return {
        ...initialState,
      };   
     default:
        return state;
  }
}
jeyeverett
  • 53
  • 3
  • Hi, thanks for advice, btw where should i put the dispatch?, in the Register Page or other pages? and put it inside useEffect or where? – Miraii App2 Aug 04 '21 at 14:23
  • The best place is probably in componentWillUnmount or the useEffect equivalent (in the return statement of useEffect) – jeyeverett Aug 04 '21 at 14:35
  • Okay, its work like i want by putting dispatch RESET_INITIAL_STATE inside the useEffect – Miraii App2 Aug 04 '21 at 18:09