redux-persist
redux-persist copied to clipboard
[need help] how to reset store & AsyncStorage when dispatch logout action ?
I am using redux-persist with redux-toolkit
I want to reset all state, persist data & AsyncStorage when the user dispatch logout action
store.js
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import rootReducers from "./rootReducers";
const persistConfig = {
key: "root",
storage: AsyncStorage,
};
const reducer = persistReducer(persistConfig, rootReducers);
export const store = configureStore({
reducer,
middleware: [
...getDefaultMiddleware({
thunk: true,
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
],
});
export const persist = persistStore(store);
You will need to call
persistor.purge()manually. To avoid circular dependancies, have a resetState function in your store.js file:export const store = createStore(rootReducer, composeMiddlewares); export const persistor = persistStore(store); export const resetStore = async () => { await persistor.purge(); store.dispatch(resetStore()); await persistor.flush(); };Then import that method wherever needed and call it.
This causes and endless loop of errors for me, any ideas?
Any solution to this? In a similar pickle.
@tomgreco I solved it by just manually resetting the state of each slice. You could probably write a for loop to clear them all. Here's how my currentUserSlice looks.
export const currentUserSlice = createSlice({
name: 'CurrentUser',
initialState,
reducers: {
setCurrentUser: (state, action) => {
state.user = action.payload;
},
updateCurrentUser: (state, action) => {
// Update the state directly.
// This will not actually mutate state because of Immer's
// implementation in Redux Toolkit, but will create a new state with the updated properties.
state.user = { ...state.user, ...action.payload };
},
removeCurrentUser: (state, action) => {
return initialState;
},
clearState: () => {
return initialState;
},
},
});
export const {
setCurrentUser,
updateCurrentUser,
removeCurrentUser,
clearState,
} = currentUserSlice.actions;