Created
May 30, 2017 08:35
-
-
Save frankchang0125/f5d5f538ebd42c97c4eae2780555ad03 to your computer and use it in GitHub Desktop.
Reset all reducers back to their initial states when user logout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
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 };
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
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().