Skip to content

Instantly share code, notes, and snippets.

@frankchang0125
Created May 30, 2017 08:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save frankchang0125/f5d5f538ebd42c97c4eae2780555ad03 to your computer and use it in GitHub Desktop.
Save frankchang0125/f5d5f538ebd42c97c4eae2780555ad03 to your computer and use it in GitHub Desktop.
Reset all reducers back to their initial states when user logout
import {combineReducers} from 'redux';
import { LOGOUT } from '../common/constants';
import { UnauthorizedErrorReducer } from '../common/commonReducers';
import FirstReducer from './FirstReducer';
import SecondReducer from './SecondReducer';
import ThirdReducer from './ThirdReducer';
/* In order to reset all reducers back to their initial states when user logout,
* rewrite rootReducer to assign 'undefined' to state when logout
*
* If state passed to reducer is 'undefined', then the next state reducer returns
* will be its initial state instead; since we have assigned it as the default value
* of reducer's state parameter
* ex: const Reducer = (state = InitialState, action) => { ... }
*
* See: https://goo.gl/GSJ98M and combineReducers() source codes for details
*/
const appReducer = combineReducers({
unauthorized: UnauthorizedErrorReducer,
first: FirstReducer,
second: SecondReducer,
third: ThirdReducer,
});
export default rootReducer = (state, action) => {
if (action.type === LOGOUT) {
state = undefined;
}
return appReducer(state, action);
};
@Surbhi-Kohli
Copy link

What if u want to reset state of just one reducer??

@frankchang0125
Copy link
Author

Haven't written Redux for a while, but I guess the key point is to pass 'undefined' to the reducer which you want to reset the state.
Therefore, you can either call the reducer directly with 'undefined' state or via combineReducers().

@andrewjuarez
Copy link

What if u want to reset state of just one reducer??

I know this question was posted over a year ago.. I found that this works

case types.LOG_OUT_USER: return { ...INITIAL_STATE };

@Chinmay-k96
Copy link

Chinmay-k96 commented Jul 4, 2021

just define a case called reset_state in the reducer where the action will be to make state = initialstate and dispatch it when you want

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment