How to reset the state of a Redux store?
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 u2
).
Imagine the following sequence of events:
User
u1
logs into the app and does something, so we cache some data in the store.User
u1
logs out.User
u2
logs into the app without refreshing the browser.
At this point, the cached data will be associated with u1
, and I would like to clean it up.
How can I reset the Redux store to its initial state when the first user logs out?
javascript redux store redux-store
add a comment |
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 u2
).
Imagine the following sequence of events:
User
u1
logs into the app and does something, so we cache some data in the store.User
u1
logs out.User
u2
logs into the app without refreshing the browser.
At this point, the cached data will be associated with u1
, and I would like to clean it up.
How can I reset the Redux store to its initial state when the first user logs out?
javascript redux store redux-store
4
It is probably better to clear the state on logout instead (from a security perspective)
– Clarkie
Feb 25 '16 at 13:38
1
Don't edit your question to include the solution. Accepting an answer is good enough. You could also self-answer with your specific solution if you feel you added a lot of stuff to the existing answers. In the meantime, I've removed the non-question portion of the post.
– ryanyuyu
Mar 1 '16 at 15:51
add a comment |
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 u2
).
Imagine the following sequence of events:
User
u1
logs into the app and does something, so we cache some data in the store.User
u1
logs out.User
u2
logs into the app without refreshing the browser.
At this point, the cached data will be associated with u1
, and I would like to clean it up.
How can I reset the Redux store to its initial state when the first user logs out?
javascript redux store redux-store
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 u2
).
Imagine the following sequence of events:
User
u1
logs into the app and does something, so we cache some data in the store.User
u1
logs out.User
u2
logs into the app without refreshing the browser.
At this point, the cached data will be associated with u1
, and I would like to clean it up.
How can I reset the Redux store to its initial state when the first user logs out?
javascript redux store redux-store
javascript redux store redux-store
edited May 13 '17 at 3:30
Aravind
22.5k75578
22.5k75578
asked Feb 25 '16 at 9:00
xyz
1,405376
1,405376
4
It is probably better to clear the state on logout instead (from a security perspective)
– Clarkie
Feb 25 '16 at 13:38
1
Don't edit your question to include the solution. Accepting an answer is good enough. You could also self-answer with your specific solution if you feel you added a lot of stuff to the existing answers. In the meantime, I've removed the non-question portion of the post.
– ryanyuyu
Mar 1 '16 at 15:51
add a comment |
4
It is probably better to clear the state on logout instead (from a security perspective)
– Clarkie
Feb 25 '16 at 13:38
1
Don't edit your question to include the solution. Accepting an answer is good enough. You could also self-answer with your specific solution if you feel you added a lot of stuff to the existing answers. In the meantime, I've removed the non-question portion of the post.
– ryanyuyu
Mar 1 '16 at 15:51
4
4
It is probably better to clear the state on logout instead (from a security perspective)
– Clarkie
Feb 25 '16 at 13:38
It is probably better to clear the state on logout instead (from a security perspective)
– Clarkie
Feb 25 '16 at 13:38
1
1
Don't edit your question to include the solution. Accepting an answer is good enough. You could also self-answer with your specific solution if you feel you added a lot of stuff to the existing answers. In the meantime, I've removed the non-question portion of the post.
– ryanyuyu
Mar 1 '16 at 15:51
Don't edit your question to include the solution. Accepting an answer is good enough. You could also self-answer with your specific solution if you feel you added a lot of stuff to the existing answers. In the meantime, I've removed the non-question portion of the post.
– ryanyuyu
Mar 1 '16 at 15:51
add a comment |
24 Answers
24
active
oldest
votes
One way to do that would be to write a root reducer in your application.
The root reducer would normally delegate handling the action to the reducer generated by combineReducers()
. However, whenever it receives USER_LOGOUT
action, it returns the initial state all over again.
For example, if your root reducer looked like this:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
You can rename it to appReducer
and write a new rootReducer
delegating to it:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
Now we just need to teach the new rootReducer
to return the initial state after USER_LOGOUT
action. As we know, reducers are supposed to return the initial state when they are called with undefined
as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state
as we pass it to appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Now, whenever USER_LOGOUT
fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type
as well.
To reiterate, the full new code looks like this:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state
before passing it to another function. Mutating a state object would be a violation of Redux principles.
In case of using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and they will be loaded from there on refresh.
First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined
and clean each storage state key.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
Object.keys(state).forEach(key => {
storage.removeItem(`persist:${key}`);
});
state = undefined;
}
return AppReducers(state, action);
};
9
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
5
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
8
Here is a version where you dynamically combine the reducers in case you use async reducers:export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
2
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
2
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once theUSER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)
– AlexKempton
Apr 20 '17 at 8:45
|
show 12 more comments
I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined
but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
13
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
1
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
2
Note that with react-redux-router, the property isrouter
and NOTrounting
– Mrchief
Feb 15 at 21:53
1
@Mrchief it depends what you defined it as in yourcombineReducers()
..... if you hadcombineReducers({routing: routingReducer})
it would be as described in the answer
– Ben Lonsdale
Jul 12 at 13:39
add a comment |
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.
i feel like this is the better approach than just setting state toundefined
like in the other answer. when your application is expecting a state tree and you give itundefined
instead, there's just more bugs and headaches to deal with than just an empty tree.
– worc
Aug 24 at 15:44
1
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
1
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
add a comment |
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
add a comment |
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
add a comment |
Combining the approaches of Dan, Ryan and Rob, to account for keeping the router
state and initializing everything else in the state tree, I ended up with this:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
add a comment |
UPDATE NGRX4
If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.
This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.
First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
Now, lets say you want to reset state from within app.module
`
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any> = [debug];
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
`
And that is basically one way to achieve the same affect with NGRX 4.
add a comment |
I've created a component to give Redux the ability of resetting state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is same as what @Dan Abramov said.
Github: https://github.com/wwayne/redux-reset
add a comment |
Just a simplified answer to the best answer:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) => (
action.type === 'USER_LOGOUT'
? rootReducer(undefined, action)
: rootReducer(state, action)
)
add a comment |
I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.
User record action
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
Logout action creator
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
Reducer
const userRecords = (state = {isFetching: false,
userRecord: , message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: }
default:
return state
}
};
I am not sure if this is optimal?
add a comment |
Just an extension to @dan-abramov answer, sometimes we may need to retain certain keys from being reset.
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
add a comment |
If you are using redux-actions, here's a quick workaround using a HOF(Higher Order Function) for handleActions
.
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
And then use handleActionsEx
instead of original handleActions
to handle reducers.
Dan's answer gives a great idea about this problem, but it didn't work out well for me, because I'm using redux-persist
.
When used with redux-persist
, simply passing undefined
state didn't trigger persisting behavior, so I knew I had to manually remove item from storage (React Native in my case, thus AsyncStorage
).
await AsyncStorage.removeItem('persist:root');
or
await persistor.flush(); // or await persistor.purge();
didn't work for me either - they just yelled at me. (e.g., complaining like "Unexpected key _persist ...")
Then I suddenly pondered all I want is just make every individual reducer return their own initial state when RESET
action type is encountered. That way, persisting is handled naturally. Obviously without above utility function (handleActionsEx
), my code won't look DRY (although it's just a one liner, i.e. RESET: () => initialState
), but I couldn't stand it 'cuz I love metaprogramming.
add a comment |
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
If you only need to reset one piece of your state tree, you could also listen forUSER_LOGOUT
in that reducer and handle it there.
– Andy_D
Jul 6 '16 at 15:46
add a comment |
why don't you just use return module.exports.default()
;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
Note: make sure you set action default value to {}
and you are ok because you don't want to encounter error when you check action.type
inside the switch statement.
add a comment |
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined
instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State> = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
add a comment |
From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage
, IndexedDB
, Web SQL
, etc) and do a hard refresh of the page using window.location.reload()
. It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window
, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.
(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
add a comment |
I found that the accepted answer worked well for me, but it triggered the ESLint no-param-reassign
error - https://eslint.org/docs/rules/no-param-reassign
Here's how I handled it instead, making sure to create a copy of the state (which is, in my understanding, the Reduxy thing to do...):
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
But maybe creating a copy of the state to just pass it into another reducer function that creates a copy of that is a little over-complicated? This doesn't read as nicely, but is more to-the-point:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
add a comment |
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined
to reducer as first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
add a comment |
In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.
add a comment |
in server, i have a variable is: global.isSsr = true
and in each reducer, i have a const is : initialState
To reset the data in the Store, I do the following with each Reducer:
example with appReducer.js:
const initialState = {
auth: {},
theme: {},
sidebar: {},
lsFanpage: {},
lsChatApp: {},
appSelected: {},
};
export default function (state = initialState, action) {
if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
}
switch (action.type) {
//...other code case here
default: {
return state;
}
}
}
finally on the server's router:
router.get('*', (req, res) => {
store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
// code ....render ssr here
});
add a comment |
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!
add a comment |
The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
Hope this helps someone else :)
add a comment |
Another option is to:
store.dispatch({type: '@@redux/INIT'})
'@@redux/INIT'
is the action type that redux dispatches automatically when you createStore
, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
add a comment |
Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.
1
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
6
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35622588%2fhow-to-reset-the-state-of-a-redux-store%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
24 Answers
24
active
oldest
votes
24 Answers
24
active
oldest
votes
active
oldest
votes
active
oldest
votes
One way to do that would be to write a root reducer in your application.
The root reducer would normally delegate handling the action to the reducer generated by combineReducers()
. However, whenever it receives USER_LOGOUT
action, it returns the initial state all over again.
For example, if your root reducer looked like this:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
You can rename it to appReducer
and write a new rootReducer
delegating to it:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
Now we just need to teach the new rootReducer
to return the initial state after USER_LOGOUT
action. As we know, reducers are supposed to return the initial state when they are called with undefined
as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state
as we pass it to appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Now, whenever USER_LOGOUT
fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type
as well.
To reiterate, the full new code looks like this:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state
before passing it to another function. Mutating a state object would be a violation of Redux principles.
In case of using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and they will be loaded from there on refresh.
First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined
and clean each storage state key.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
Object.keys(state).forEach(key => {
storage.removeItem(`persist:${key}`);
});
state = undefined;
}
return AppReducers(state, action);
};
9
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
5
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
8
Here is a version where you dynamically combine the reducers in case you use async reducers:export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
2
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
2
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once theUSER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)
– AlexKempton
Apr 20 '17 at 8:45
|
show 12 more comments
One way to do that would be to write a root reducer in your application.
The root reducer would normally delegate handling the action to the reducer generated by combineReducers()
. However, whenever it receives USER_LOGOUT
action, it returns the initial state all over again.
For example, if your root reducer looked like this:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
You can rename it to appReducer
and write a new rootReducer
delegating to it:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
Now we just need to teach the new rootReducer
to return the initial state after USER_LOGOUT
action. As we know, reducers are supposed to return the initial state when they are called with undefined
as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state
as we pass it to appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Now, whenever USER_LOGOUT
fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type
as well.
To reiterate, the full new code looks like this:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state
before passing it to another function. Mutating a state object would be a violation of Redux principles.
In case of using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and they will be loaded from there on refresh.
First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined
and clean each storage state key.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
Object.keys(state).forEach(key => {
storage.removeItem(`persist:${key}`);
});
state = undefined;
}
return AppReducers(state, action);
};
9
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
5
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
8
Here is a version where you dynamically combine the reducers in case you use async reducers:export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
2
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
2
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once theUSER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)
– AlexKempton
Apr 20 '17 at 8:45
|
show 12 more comments
One way to do that would be to write a root reducer in your application.
The root reducer would normally delegate handling the action to the reducer generated by combineReducers()
. However, whenever it receives USER_LOGOUT
action, it returns the initial state all over again.
For example, if your root reducer looked like this:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
You can rename it to appReducer
and write a new rootReducer
delegating to it:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
Now we just need to teach the new rootReducer
to return the initial state after USER_LOGOUT
action. As we know, reducers are supposed to return the initial state when they are called with undefined
as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state
as we pass it to appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Now, whenever USER_LOGOUT
fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type
as well.
To reiterate, the full new code looks like this:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state
before passing it to another function. Mutating a state object would be a violation of Redux principles.
In case of using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and they will be loaded from there on refresh.
First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined
and clean each storage state key.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
Object.keys(state).forEach(key => {
storage.removeItem(`persist:${key}`);
});
state = undefined;
}
return AppReducers(state, action);
};
One way to do that would be to write a root reducer in your application.
The root reducer would normally delegate handling the action to the reducer generated by combineReducers()
. However, whenever it receives USER_LOGOUT
action, it returns the initial state all over again.
For example, if your root reducer looked like this:
const rootReducer = combineReducers({
/* your app’s top-level reducers */
})
You can rename it to appReducer
and write a new rootReducer
delegating to it:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
return appReducer(state, action)
}
Now we just need to teach the new rootReducer
to return the initial state after USER_LOGOUT
action. As we know, reducers are supposed to return the initial state when they are called with undefined
as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state
as we pass it to appReducer
:
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Now, whenever USER_LOGOUT
fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type
as well.
To reiterate, the full new code looks like this:
const appReducer = combineReducers({
/* your app’s top-level reducers */
})
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state = undefined
}
return appReducer(state, action)
}
Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state
before passing it to another function. Mutating a state object would be a violation of Redux principles.
In case of using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and they will be loaded from there on refresh.
First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined
and clean each storage state key.
const rootReducer = (state, action) => {
if (action.type === SIGNOUT_REQUEST) {
Object.keys(state).forEach(key => {
storage.removeItem(`persist:${key}`);
});
state = undefined;
}
return AppReducers(state, action);
};
edited Nov 19 at 8:39
barbsan
2,14811122
2,14811122
answered Feb 26 '16 at 1:54
Dan Abramov
171k48306444
171k48306444
9
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
5
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
8
Here is a version where you dynamically combine the reducers in case you use async reducers:export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
2
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
2
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once theUSER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)
– AlexKempton
Apr 20 '17 at 8:45
|
show 12 more comments
9
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
5
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
8
Here is a version where you dynamically combine the reducers in case you use async reducers:export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
2
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
2
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once theUSER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)
– AlexKempton
Apr 20 '17 at 8:45
9
9
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.
case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
I'm curious Dan, could you also do something like this in your reducer. with CLEAR_DATA being the action.
case 'CLEAR_DATA': return initialState
– HussienK
Jul 20 '16 at 15:29
5
5
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
@HussienK that would work but not on the state for every reducer.
– Cory Danielson
Aug 15 '16 at 22:14
8
8
Here is a version where you dynamically combine the reducers in case you use async reducers:
export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
Here is a version where you dynamically combine the reducers in case you use async reducers:
export const createRootReducer = asyncReducers => { const appReducer = combineReducers({ myReducer ...asyncReducers }); return (state, action) => { if (action.type === 'LOGOUT_USER') { state = undefined; } return appReducer(state, action); } };
– Ivo Sabev
Aug 31 '16 at 15:06
2
2
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
if (action.type === 'RESET') return action.stateFromLocalStorage
– Dan Abramov
Dec 10 '16 at 22:46
2
2
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once the
USER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)– AlexKempton
Apr 20 '17 at 8:45
Does this approach completely clear the state and all of its history? I'm thinking from a security perspective: If this has been implemented, once the
USER_LOGOUT
action has been fired, is it possible to obtain state data from earlier on? (e.g. via devtools)– AlexKempton
Apr 20 '17 at 8:45
|
show 12 more comments
I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined
but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
13
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
1
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
2
Note that with react-redux-router, the property isrouter
and NOTrounting
– Mrchief
Feb 15 at 21:53
1
@Mrchief it depends what you defined it as in yourcombineReducers()
..... if you hadcombineReducers({routing: routingReducer})
it would be as described in the answer
– Ben Lonsdale
Jul 12 at 13:39
add a comment |
I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined
but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
13
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
1
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
2
Note that with react-redux-router, the property isrouter
and NOTrounting
– Mrchief
Feb 15 at 21:53
1
@Mrchief it depends what you defined it as in yourcombineReducers()
..... if you hadcombineReducers({routing: routingReducer})
it would be as described in the answer
– Ben Lonsdale
Jul 12 at 13:39
add a comment |
I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined
but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined
but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
const { routing } = state
state = { routing }
}
return appReducer(state, action)
}
edited Dec 17 '16 at 2:13
jabacchetta
2,6351733
2,6351733
answered May 20 '16 at 5:27
Ryan Irilli
74163
74163
13
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
1
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
2
Note that with react-redux-router, the property isrouter
and NOTrounting
– Mrchief
Feb 15 at 21:53
1
@Mrchief it depends what you defined it as in yourcombineReducers()
..... if you hadcombineReducers({routing: routingReducer})
it would be as described in the answer
– Ben Lonsdale
Jul 12 at 13:39
add a comment |
13
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
1
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
2
Note that with react-redux-router, the property isrouter
and NOTrounting
– Mrchief
Feb 15 at 21:53
1
@Mrchief it depends what you defined it as in yourcombineReducers()
..... if you hadcombineReducers({routing: routingReducer})
it would be as described in the answer
– Ben Lonsdale
Jul 12 at 13:39
13
13
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
I think the takeaway here is that you may not want to clear the whole state tree on logout - the approach works equally well at the root reducer of any subtree, and so it may be clearer to apply this technique only at the root reducers of the subtree(s) you do want to clear, rather than picking out 'special' children to not clear at the root reducer of the entire tree, like this
– davnicwil
Sep 6 '16 at 18:51
1
1
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
I think i am experiencing this issues you are referring to right now, (where on logout it will set the rout to the right path but a complete different component would load) i implemented something similar to yours to fix it, but i think something with immutable js is massing this up. I ended up creating a parent reducer that has RESET-STATE action, and i inherit from that reducer to avoid touching routing altogether
– Neta Meta
Oct 19 '17 at 12:32
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
Was experiencing similar issues, this has fixed it. Thanks.
– Lloyd Watkin
Jan 15 at 10:10
2
2
Note that with react-redux-router, the property is
router
and NOT rounting
– Mrchief
Feb 15 at 21:53
Note that with react-redux-router, the property is
router
and NOT rounting
– Mrchief
Feb 15 at 21:53
1
1
@Mrchief it depends what you defined it as in your
combineReducers()
..... if you had combineReducers({routing: routingReducer})
it would be as described in the answer– Ben Lonsdale
Jul 12 at 13:39
@Mrchief it depends what you defined it as in your
combineReducers()
..... if you had combineReducers({routing: routingReducer})
it would be as described in the answer– Ben Lonsdale
Jul 12 at 13:39
add a comment |
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.
i feel like this is the better approach than just setting state toundefined
like in the other answer. when your application is expecting a state tree and you give itundefined
instead, there's just more bugs and headaches to deal with than just an empty tree.
– worc
Aug 24 at 15:44
1
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
1
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
add a comment |
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.
i feel like this is the better approach than just setting state toundefined
like in the other answer. when your application is expecting a state tree and you give itundefined
instead, there's just more bugs and headaches to deal with than just an empty tree.
– worc
Aug 24 at 15:44
1
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
1
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
add a comment |
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.
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.
answered Dec 27 '17 at 19:17
nirbhaygp
30126
30126
i feel like this is the better approach than just setting state toundefined
like in the other answer. when your application is expecting a state tree and you give itundefined
instead, there's just more bugs and headaches to deal with than just an empty tree.
– worc
Aug 24 at 15:44
1
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
1
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
add a comment |
i feel like this is the better approach than just setting state toundefined
like in the other answer. when your application is expecting a state tree and you give itundefined
instead, there's just more bugs and headaches to deal with than just an empty tree.
– worc
Aug 24 at 15:44
1
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
1
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
i feel like this is the better approach than just setting state to
undefined
like in the other answer. when your application is expecting a state tree and you give it undefined
instead, there's just more bugs and headaches to deal with than just an empty tree.– worc
Aug 24 at 15:44
i feel like this is the better approach than just setting state to
undefined
like in the other answer. when your application is expecting a state tree and you give it undefined
instead, there's just more bugs and headaches to deal with than just an empty tree.– worc
Aug 24 at 15:44
1
1
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
@worc The state won't actually be undefined, because reducers return initialState when they receive an undefined state
– Guillaume
Aug 29 at 14:30
1
1
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
@worc think that with this approach, each time anyone create a new reducer you will have to remember to add the reset case.
– Francute
Dec 10 at 16:24
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
i've definitely changed my mind on this, for both those reasons, plus the idea that a RESET_ACTION is an action. so it doesn't really belong in the reducer to begin with.
– worc
Dec 10 at 18:19
add a comment |
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
add a comment |
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
add a comment |
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
answered Nov 25 '16 at 12:24
Daniel petrov
492612
492612
add a comment |
add a comment |
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
add a comment |
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
add a comment |
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
With Redux if have applied the following solution, which assumes I have set an initialState in all my reducers (e.g. { user: { name, email }}). In many components I check on these nested properties, so with this fix I prevent my renders methods are broken on coupled property conditions (e.g. if state.user.email, which will throw an error user is undefined if upper mentioned solutions).
const appReducer = combineReducers({
tabs,
user
})
const initialState = appReducer({}, {})
const rootReducer = (state, action) => {
if (action.type === 'LOG_OUT') {
state = initialState
}
return appReducer(state, action)
}
answered Jul 5 '16 at 9:07
Rob Moorman
10113
10113
add a comment |
add a comment |
Combining the approaches of Dan, Ryan and Rob, to account for keeping the router
state and initializing everything else in the state tree, I ended up with this:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
add a comment |
Combining the approaches of Dan, Ryan and Rob, to account for keeping the router
state and initializing everything else in the state tree, I ended up with this:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
add a comment |
Combining the approaches of Dan, Ryan and Rob, to account for keeping the router
state and initializing everything else in the state tree, I ended up with this:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
Combining the approaches of Dan, Ryan and Rob, to account for keeping the router
state and initializing everything else in the state tree, I ended up with this:
const rootReducer = (state, action) => appReducer(action.type === LOGOUT ? {
...appReducer({}, {}),
router: state && state.router || {}
} : state, action);
answered Jul 6 '16 at 15:42
Andy_D
2,4401215
2,4401215
add a comment |
add a comment |
UPDATE NGRX4
If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.
This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.
First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
Now, lets say you want to reset state from within app.module
`
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any> = [debug];
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
`
And that is basically one way to achieve the same affect with NGRX 4.
add a comment |
UPDATE NGRX4
If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.
This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.
First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
Now, lets say you want to reset state from within app.module
`
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any> = [debug];
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
`
And that is basically one way to achieve the same affect with NGRX 4.
add a comment |
UPDATE NGRX4
If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.
This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.
First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
Now, lets say you want to reset state from within app.module
`
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any> = [debug];
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
`
And that is basically one way to achieve the same affect with NGRX 4.
UPDATE NGRX4
If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.
This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.
First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:
//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.reducer,
layout: fromLayout.reducer,
users: fromUsers.reducer,
networks: fromNetworks.reducer,
routingDisplay: fromRoutingDisplay.reducer,
routing: fromRouting.reducer,
routes: fromRoutes.reducer,
routesFilter: fromRoutesFilter.reducer,
params: fromParams.reducer
}
Now, lets say you want to reset state from within app.module
`
//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
return function(state, action) {
switch (action.type) {
case fromAuth.LOGOUT:
console.log("logout action");
state = undefined;
}
return reducer(state, action);
}
}
export const metaReducers: MetaReducer<any> = [debug];
@NgModule({
imports: [
...
StoreModule.forRoot(reducers, { metaReducers}),
...
]
})
export class AppModule { }
`
And that is basically one way to achieve the same affect with NGRX 4.
answered Sep 7 '17 at 15:22
Tyler Brown
159311
159311
add a comment |
add a comment |
I've created a component to give Redux the ability of resetting state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is same as what @Dan Abramov said.
Github: https://github.com/wwayne/redux-reset
add a comment |
I've created a component to give Redux the ability of resetting state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is same as what @Dan Abramov said.
Github: https://github.com/wwayne/redux-reset
add a comment |
I've created a component to give Redux the ability of resetting state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is same as what @Dan Abramov said.
Github: https://github.com/wwayne/redux-reset
I've created a component to give Redux the ability of resetting state, you just need to use this component to enhance your store and dispatch a specific action.type to trigger reset. The thought of implementation is same as what @Dan Abramov said.
Github: https://github.com/wwayne/redux-reset
answered Mar 26 '16 at 17:03
wwayne
958
958
add a comment |
add a comment |
Just a simplified answer to the best answer:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) => (
action.type === 'USER_LOGOUT'
? rootReducer(undefined, action)
: rootReducer(state, action)
)
add a comment |
Just a simplified answer to the best answer:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) => (
action.type === 'USER_LOGOUT'
? rootReducer(undefined, action)
: rootReducer(state, action)
)
add a comment |
Just a simplified answer to the best answer:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) => (
action.type === 'USER_LOGOUT'
? rootReducer(undefined, action)
: rootReducer(state, action)
)
Just a simplified answer to the best answer:
const rootReducer = combineReducers({
auth: authReducer,
...formReducers,
routing
});
export default (state, action) => (
action.type === 'USER_LOGOUT'
? rootReducer(undefined, action)
: rootReducer(state, action)
)
answered Aug 13 at 21:54
matt carlotta
2,02749
2,02749
add a comment |
add a comment |
I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.
User record action
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
Logout action creator
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
Reducer
const userRecords = (state = {isFetching: false,
userRecord: , message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: }
default:
return state
}
};
I am not sure if this is optimal?
add a comment |
I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.
User record action
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
Logout action creator
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
Reducer
const userRecords = (state = {isFetching: false,
userRecord: , message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: }
default:
return state
}
};
I am not sure if this is optimal?
add a comment |
I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.
User record action
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
Logout action creator
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
Reducer
const userRecords = (state = {isFetching: false,
userRecord: , message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: }
default:
return state
}
};
I am not sure if this is optimal?
I have created actions to clear state. So when I dispatch a logout action creator I dispatch actions to clear state as well.
User record action
export const clearUserRecord = () => ({
type: CLEAR_USER_RECORD
});
Logout action creator
export const logoutUser = () => {
return dispatch => {
dispatch(requestLogout())
dispatch(receiveLogout())
localStorage.removeItem('auth_token')
dispatch({ type: 'CLEAR_USER_RECORD' })
}
};
Reducer
const userRecords = (state = {isFetching: false,
userRecord: , message: ''}, action) => {
switch (action.type) {
case REQUEST_USER_RECORD:
return { ...state,
isFetching: true}
case RECEIVE_USER_RECORD:
return { ...state,
isFetching: false,
userRecord: action.user_record}
case USER_RECORD_ERROR:
return { ...state,
isFetching: false,
message: action.message}
case CLEAR_USER_RECORD:
return {...state,
isFetching: false,
message: '',
userRecord: }
default:
return state
}
};
I am not sure if this is optimal?
answered Sep 19 '16 at 20:02
Navinesh Chand
211
211
add a comment |
add a comment |
Just an extension to @dan-abramov answer, sometimes we may need to retain certain keys from being reset.
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
add a comment |
Just an extension to @dan-abramov answer, sometimes we may need to retain certain keys from being reset.
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
add a comment |
Just an extension to @dan-abramov answer, sometimes we may need to retain certain keys from being reset.
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
Just an extension to @dan-abramov answer, sometimes we may need to retain certain keys from being reset.
const retainKeys = ['appConfig'];
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT_USER_SUCCESS' && state) {
state = !isEmpty(retainKeys) ? pick(state, retainKeys) : undefined;
}
return appReducer(state, action);
};
answered Mar 13 at 1:56
gsaandy
113
113
add a comment |
add a comment |
If you are using redux-actions, here's a quick workaround using a HOF(Higher Order Function) for handleActions
.
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
And then use handleActionsEx
instead of original handleActions
to handle reducers.
Dan's answer gives a great idea about this problem, but it didn't work out well for me, because I'm using redux-persist
.
When used with redux-persist
, simply passing undefined
state didn't trigger persisting behavior, so I knew I had to manually remove item from storage (React Native in my case, thus AsyncStorage
).
await AsyncStorage.removeItem('persist:root');
or
await persistor.flush(); // or await persistor.purge();
didn't work for me either - they just yelled at me. (e.g., complaining like "Unexpected key _persist ...")
Then I suddenly pondered all I want is just make every individual reducer return their own initial state when RESET
action type is encountered. That way, persisting is handled naturally. Obviously without above utility function (handleActionsEx
), my code won't look DRY (although it's just a one liner, i.e. RESET: () => initialState
), but I couldn't stand it 'cuz I love metaprogramming.
add a comment |
If you are using redux-actions, here's a quick workaround using a HOF(Higher Order Function) for handleActions
.
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
And then use handleActionsEx
instead of original handleActions
to handle reducers.
Dan's answer gives a great idea about this problem, but it didn't work out well for me, because I'm using redux-persist
.
When used with redux-persist
, simply passing undefined
state didn't trigger persisting behavior, so I knew I had to manually remove item from storage (React Native in my case, thus AsyncStorage
).
await AsyncStorage.removeItem('persist:root');
or
await persistor.flush(); // or await persistor.purge();
didn't work for me either - they just yelled at me. (e.g., complaining like "Unexpected key _persist ...")
Then I suddenly pondered all I want is just make every individual reducer return their own initial state when RESET
action type is encountered. That way, persisting is handled naturally. Obviously without above utility function (handleActionsEx
), my code won't look DRY (although it's just a one liner, i.e. RESET: () => initialState
), but I couldn't stand it 'cuz I love metaprogramming.
add a comment |
If you are using redux-actions, here's a quick workaround using a HOF(Higher Order Function) for handleActions
.
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
And then use handleActionsEx
instead of original handleActions
to handle reducers.
Dan's answer gives a great idea about this problem, but it didn't work out well for me, because I'm using redux-persist
.
When used with redux-persist
, simply passing undefined
state didn't trigger persisting behavior, so I knew I had to manually remove item from storage (React Native in my case, thus AsyncStorage
).
await AsyncStorage.removeItem('persist:root');
or
await persistor.flush(); // or await persistor.purge();
didn't work for me either - they just yelled at me. (e.g., complaining like "Unexpected key _persist ...")
Then I suddenly pondered all I want is just make every individual reducer return their own initial state when RESET
action type is encountered. That way, persisting is handled naturally. Obviously without above utility function (handleActionsEx
), my code won't look DRY (although it's just a one liner, i.e. RESET: () => initialState
), but I couldn't stand it 'cuz I love metaprogramming.
If you are using redux-actions, here's a quick workaround using a HOF(Higher Order Function) for handleActions
.
import { handleActions } from 'redux-actions';
export function handleActionsEx(reducer, initialState) {
const enhancedReducer = {
...reducer,
RESET: () => initialState
};
return handleActions(enhancedReducer, initialState);
}
And then use handleActionsEx
instead of original handleActions
to handle reducers.
Dan's answer gives a great idea about this problem, but it didn't work out well for me, because I'm using redux-persist
.
When used with redux-persist
, simply passing undefined
state didn't trigger persisting behavior, so I knew I had to manually remove item from storage (React Native in my case, thus AsyncStorage
).
await AsyncStorage.removeItem('persist:root');
or
await persistor.flush(); // or await persistor.purge();
didn't work for me either - they just yelled at me. (e.g., complaining like "Unexpected key _persist ...")
Then I suddenly pondered all I want is just make every individual reducer return their own initial state when RESET
action type is encountered. That way, persisting is handled naturally. Obviously without above utility function (handleActionsEx
), my code won't look DRY (although it's just a one liner, i.e. RESET: () => initialState
), but I couldn't stand it 'cuz I love metaprogramming.
answered Apr 26 at 11:06
elquimista
80911025
80911025
add a comment |
add a comment |
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
If you only need to reset one piece of your state tree, you could also listen forUSER_LOGOUT
in that reducer and handle it there.
– Andy_D
Jul 6 '16 at 15:46
add a comment |
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
If you only need to reset one piece of your state tree, you could also listen forUSER_LOGOUT
in that reducer and handle it there.
– Andy_D
Jul 6 '16 at 15:46
add a comment |
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
This approach is very right: Destruct any specific state "NAME" to ignore and keep others.
const rootReducer = (state, action) => {
if (action.type === 'USER_LOGOUT') {
state.NAME = undefined
}
return appReducer(state, action)
}
edited May 31 '16 at 8:35
Tunaki
88.4k22191262
88.4k22191262
answered May 31 '16 at 8:25
khalil zaidoun
1
1
If you only need to reset one piece of your state tree, you could also listen forUSER_LOGOUT
in that reducer and handle it there.
– Andy_D
Jul 6 '16 at 15:46
add a comment |
If you only need to reset one piece of your state tree, you could also listen forUSER_LOGOUT
in that reducer and handle it there.
– Andy_D
Jul 6 '16 at 15:46
If you only need to reset one piece of your state tree, you could also listen for
USER_LOGOUT
in that reducer and handle it there.– Andy_D
Jul 6 '16 at 15:46
If you only need to reset one piece of your state tree, you could also listen for
USER_LOGOUT
in that reducer and handle it there.– Andy_D
Jul 6 '16 at 15:46
add a comment |
why don't you just use return module.exports.default()
;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
Note: make sure you set action default value to {}
and you are ok because you don't want to encounter error when you check action.type
inside the switch statement.
add a comment |
why don't you just use return module.exports.default()
;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
Note: make sure you set action default value to {}
and you are ok because you don't want to encounter error when you check action.type
inside the switch statement.
add a comment |
why don't you just use return module.exports.default()
;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
Note: make sure you set action default value to {}
and you are ok because you don't want to encounter error when you check action.type
inside the switch statement.
why don't you just use return module.exports.default()
;)
export default (state = {pending: false, error: null}, action = {}) => {
switch (action.type) {
case "RESET_POST":
return module.exports.default();
case "SEND_POST_PENDING":
return {...state, pending: true, error: null};
// ....
}
return state;
}
Note: make sure you set action default value to {}
and you are ok because you don't want to encounter error when you check action.type
inside the switch statement.
answered Dec 2 '16 at 17:08
Fareed Alnamrouti
19.7k26155
19.7k26155
add a comment |
add a comment |
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined
instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State> = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
add a comment |
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined
instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State> = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
add a comment |
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined
instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State> = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
The following solution worked for me.
I added resetting state function to meta reducers.The key was to use
return reducer(undefined, action);
to set all reducers to initial state. Returning undefined
instead was causing errors due to the fact that the structure of the store has been destroyed.
/reducers/index.ts
export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
return function (state: State, action: Action): State {
switch (action.type) {
case AuthActionTypes.Logout: {
return reducer(undefined, action);
}
default: {
return reducer(state, action);
}
}
};
}
export const metaReducers: MetaReducer<State> = [ resetState ];
app.module.ts
import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule {}
answered May 7 at 10:16
Pan Piotr
31
31
add a comment |
add a comment |
From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage
, IndexedDB
, Web SQL
, etc) and do a hard refresh of the page using window.location.reload()
. It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window
, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.
(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
add a comment |
From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage
, IndexedDB
, Web SQL
, etc) and do a hard refresh of the page using window.location.reload()
. It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window
, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.
(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
add a comment |
From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage
, IndexedDB
, Web SQL
, etc) and do a hard refresh of the page using window.location.reload()
. It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window
, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.
(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)
From a security perspective, the safest thing to do when logging a user out is to reset all persistent state (e.x. cookies, localStorage
, IndexedDB
, Web SQL
, etc) and do a hard refresh of the page using window.location.reload()
. It's possible a sloppy developer accidentally or intentionally stored some sensitive data on window
, in the DOM, etc. Blowing away all persistent state and refreshing the browser is the only way to guarantee no information from the previous user is leaked to the next user.
(Of course, as a user on a shared computer you should use "private browsing" mode, close the browser window yourself, use the "clear browsing data" function, etc, but as a developer we can't expect everyone to always be that diligent)
edited May 9 at 23:46
answered May 9 at 23:41
tlrobinson
1,4932031
1,4932031
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
add a comment |
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:00
add a comment |
I found that the accepted answer worked well for me, but it triggered the ESLint no-param-reassign
error - https://eslint.org/docs/rules/no-param-reassign
Here's how I handled it instead, making sure to create a copy of the state (which is, in my understanding, the Reduxy thing to do...):
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
But maybe creating a copy of the state to just pass it into another reducer function that creates a copy of that is a little over-complicated? This doesn't read as nicely, but is more to-the-point:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
add a comment |
I found that the accepted answer worked well for me, but it triggered the ESLint no-param-reassign
error - https://eslint.org/docs/rules/no-param-reassign
Here's how I handled it instead, making sure to create a copy of the state (which is, in my understanding, the Reduxy thing to do...):
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
But maybe creating a copy of the state to just pass it into another reducer function that creates a copy of that is a little over-complicated? This doesn't read as nicely, but is more to-the-point:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
add a comment |
I found that the accepted answer worked well for me, but it triggered the ESLint no-param-reassign
error - https://eslint.org/docs/rules/no-param-reassign
Here's how I handled it instead, making sure to create a copy of the state (which is, in my understanding, the Reduxy thing to do...):
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
But maybe creating a copy of the state to just pass it into another reducer function that creates a copy of that is a little over-complicated? This doesn't read as nicely, but is more to-the-point:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
I found that the accepted answer worked well for me, but it triggered the ESLint no-param-reassign
error - https://eslint.org/docs/rules/no-param-reassign
Here's how I handled it instead, making sure to create a copy of the state (which is, in my understanding, the Reduxy thing to do...):
import { combineReducers } from "redux"
import { routerReducer } from "react-router-redux"
import ws from "reducers/ws"
import session from "reducers/session"
import app from "reducers/app"
const appReducer = combineReducers({
"routing": routerReducer,
ws,
session,
app
})
export default (state, action) => {
const stateCopy = action.type === "LOGOUT" ? undefined : { ...state }
return appReducer(stateCopy, action)
}
But maybe creating a copy of the state to just pass it into another reducer function that creates a copy of that is a little over-complicated? This doesn't read as nicely, but is more to-the-point:
export default (state, action) => {
return appReducer(action.type === "LOGOUT" ? undefined : state, action)
}
answered Jun 4 at 20:15
skwidbreth
2,39711554
2,39711554
add a comment |
add a comment |
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined
to reducer as first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
add a comment |
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined
to reducer as first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
add a comment |
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined
to reducer as first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
My workaround when working with typescript, built on top of Dan's answer (redux typings make it impossible to pass undefined
to reducer as first argument, so I cache initial root state in a constant):
// store
export const store: Store<IStoreState> = createStore(
rootReducer,
storeEnhacer,
)
export const initialRootState = {
...store.getState(),
}
// root reducer
const appReducer = combineReducers<IStoreState>(reducers)
export const rootReducer = (state: IStoreState, action: IAction<any>) => {
if (action.type === "USER_LOGOUT") {
return appReducer(initialRootState, action)
}
return appReducer(state, action)
}
// auth service
class Auth {
...
logout() {
store.dispatch({type: "USER_LOGOUT"})
}
}
answered Jun 12 at 14:09
Jacka
65821026
65821026
add a comment |
add a comment |
In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.
add a comment |
In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.
add a comment |
In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.
In addition to Dan Abramov's answer, shouldn't we explicitly set action as action = {type: '@@INIT'} alongside state = undefined. With above action type, every reducer returns the initial state.
answered Jul 14 at 9:50
rupav jain
1717
1717
add a comment |
add a comment |
in server, i have a variable is: global.isSsr = true
and in each reducer, i have a const is : initialState
To reset the data in the Store, I do the following with each Reducer:
example with appReducer.js:
const initialState = {
auth: {},
theme: {},
sidebar: {},
lsFanpage: {},
lsChatApp: {},
appSelected: {},
};
export default function (state = initialState, action) {
if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
}
switch (action.type) {
//...other code case here
default: {
return state;
}
}
}
finally on the server's router:
router.get('*', (req, res) => {
store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
// code ....render ssr here
});
add a comment |
in server, i have a variable is: global.isSsr = true
and in each reducer, i have a const is : initialState
To reset the data in the Store, I do the following with each Reducer:
example with appReducer.js:
const initialState = {
auth: {},
theme: {},
sidebar: {},
lsFanpage: {},
lsChatApp: {},
appSelected: {},
};
export default function (state = initialState, action) {
if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
}
switch (action.type) {
//...other code case here
default: {
return state;
}
}
}
finally on the server's router:
router.get('*', (req, res) => {
store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
// code ....render ssr here
});
add a comment |
in server, i have a variable is: global.isSsr = true
and in each reducer, i have a const is : initialState
To reset the data in the Store, I do the following with each Reducer:
example with appReducer.js:
const initialState = {
auth: {},
theme: {},
sidebar: {},
lsFanpage: {},
lsChatApp: {},
appSelected: {},
};
export default function (state = initialState, action) {
if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
}
switch (action.type) {
//...other code case here
default: {
return state;
}
}
}
finally on the server's router:
router.get('*', (req, res) => {
store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
// code ....render ssr here
});
in server, i have a variable is: global.isSsr = true
and in each reducer, i have a const is : initialState
To reset the data in the Store, I do the following with each Reducer:
example with appReducer.js:
const initialState = {
auth: {},
theme: {},
sidebar: {},
lsFanpage: {},
lsChatApp: {},
appSelected: {},
};
export default function (state = initialState, action) {
if (typeof isSsr!=="undefined" && isSsr) { //<== using global.isSsr = true
state = {...initialState};//<= important "will reset the data every time there is a request from the client to the server"
}
switch (action.type) {
//...other code case here
default: {
return state;
}
}
}
finally on the server's router:
router.get('*', (req, res) => {
store.dispatch({type:'reset-all-blabla'});//<= unlike any action.type // i use Math.random()
// code ....render ssr here
});
edited Aug 11 at 7:31
answered Aug 11 at 6:38
Ngannv
48546
48546
add a comment |
add a comment |
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!
add a comment |
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!
add a comment |
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!
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!
edited Aug 19 at 13:47
answered Aug 18 at 14:25
Mukundhan
608511
608511
add a comment |
add a comment |
The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
Hope this helps someone else :)
add a comment |
The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
Hope this helps someone else :)
add a comment |
The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
Hope this helps someone else :)
The accepted answer helped me solve my case. However, I encountered case where not-the-whole-state had to be cleared. So - I did it this way:
const combinedReducer = combineReducers({
// my reducers
});
const rootReducer = (state, action) => {
if (action.type === RESET_REDUX_STATE) {
// clear everything but keep the stuff we want to be preserved ..
delete state.something;
delete state.anotherThing;
}
return combinedReducer(state, action);
}
export default rootReducer;
Hope this helps someone else :)
answered Nov 22 at 18:36
pesho hristov
638826
638826
add a comment |
add a comment |
Another option is to:
store.dispatch({type: '@@redux/INIT'})
'@@redux/INIT'
is the action type that redux dispatches automatically when you createStore
, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
add a comment |
Another option is to:
store.dispatch({type: '@@redux/INIT'})
'@@redux/INIT'
is the action type that redux dispatches automatically when you createStore
, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
add a comment |
Another option is to:
store.dispatch({type: '@@redux/INIT'})
'@@redux/INIT'
is the action type that redux dispatches automatically when you createStore
, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...
Another option is to:
store.dispatch({type: '@@redux/INIT'})
'@@redux/INIT'
is the action type that redux dispatches automatically when you createStore
, so assuming your reducers all have a default already, this would get caught by those and start your state off fresh. It might be considered a private implementation detail of redux, though, so buyer beware...
answered May 30 '17 at 16:26
lobati
2,45532140
2,45532140
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
add a comment |
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
I did that it's not changing state, also I tried @@INIT which is shown in ReduxDevtools as first action
– RezaRahmati
Jun 13 '17 at 15:09
add a comment |
Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.
1
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
6
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
add a comment |
Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.
1
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
6
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
add a comment |
Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.
Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.
answered Feb 26 '16 at 15:40
user3500325
67
67
1
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
6
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
add a comment |
1
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
6
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
1
1
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
What if you use a middleware that syncs the store to localstorage? Then your approach doesn't work at all...
– Spock
Sep 10 '16 at 11:43
6
6
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
I don't really understand why people downvote answers like this.
– Wylliam Judd
Feb 7 at 17:06
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
Why have people downvoted this? When you do a new redux state, with empty content, you basically still have the previous states in memory, and you could theoretically access the data from them. Refreshing the browser IS your safest bet!
– Wilhelm Sorban
Dec 7 at 17:03
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35622588%2fhow-to-reset-the-state-of-a-redux-store%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
It is probably better to clear the state on logout instead (from a security perspective)
– Clarkie
Feb 25 '16 at 13:38
1
Don't edit your question to include the solution. Accepting an answer is good enough. You could also self-answer with your specific solution if you feel you added a lot of stuff to the existing answers. In the meantime, I've removed the non-question portion of the post.
– ryanyuyu
Mar 1 '16 at 15:51