How do I clear state on logout
prateekkarki opened this issue · 2 comments
prateekkarki commented
I have the same problem as addressed in the following question.
https://stackoverflow.com/questions/35622588/how-to-reset-the-state-of-a-redux-store
I need to clear all the redux state on logout, but since my logout is on a separate global slice it can only affect the global slice and not other redux states. How do I clear all other states calling an action from global state?
Here's how I combine reducers:
import { combineReducers } from '@reduxjs/toolkit';
export function createReducer(injectedReducers = {}) {
if (Object.keys(injectedReducers).length === 0) {
return state => state;
}
return combineReducers({
...injectedReducers
});
}
my globalReducer:
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
loading: false
};
const globalSlice = createSlice({
name: 'global',
initialState,
reducers: {
logout(state) {
return state;
}
}
});
export const { actions, reducer, name: sliceKey } = globalSlice;
my store/index.js
import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';
import { createInjectorsEnhancer, forceReducerReload } from 'redux-injectors';
import createSagaMiddleware from 'redux-saga';
import { createReducer } from './reducers';
function configureAppStore() {
const reduxSagaMonitorOptions = {
onError: (error, { sagaStack }) => {
// console.log(error, sagaStack);
}
};
const sagaMiddleware = createSagaMiddleware(reduxSagaMonitorOptions);
const { run: runSaga } = sagaMiddleware;
// Create the store with saga middleware
const middlewares = [sagaMiddleware];
const enhancers = [
createInjectorsEnhancer({
createReducer,
runSaga
})
];
const store = configureStore({
reducer: createReducer(),
middleware: [
...getDefaultMiddleware({
serializableCheck: {
ignoredActionPaths: ['payload.history']
},
immutableCheck: false
}),
...middlewares
],
devTools:
process.env.NODE_ENV !== 'production'
|| process.env.PUBLIC_URL.length > 0,
enhancers
});
// Make reducers hot reloadable, see http://mxs.is/googmo
if (module.hot) {
module.hot.accept('./reducers', () => {
forceReducerReload(store);
});
}
return store;
}
export const store = configureAppStore();
BenLorantfy commented
@prateekkarki what about something like this:
export function createReducer(injectedReducers = {}) {
if (Object.keys(injectedReducers).length === 0) {
return state => state;
}
const combinedReducer = combineReducers({
...injectedReducers
});
return (state, action) => {
if (action.type === 'USER_LOGOUT') {
return combinedReducer(undefined, action)
}
return combinedReducer(state, action)
}
}
BenLorantfy commented
@prateekkarki I'm going to close this for house keeping purposes. Let me know if the above works for you