rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.94k stars 866 forks source link

[help needed] Data getting restored to reducer after app launch #1291

Open aravi365 opened 3 years ago

aravi365 commented 3 years ago

Data stored initially gets replaced with new data after logout and when app is restarted or refreshed the initial stored data is retrieved back to reducer instead of the second set of stored data or reducer initial states.

Here is my store config code:

import {createStore, compose, applyMiddleware} from 'redux';
import {persistStore, persistCombineReducers} from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import {createLogger} from 'redux-logger';
import createSagaMiddleware from 'redux-saga';

import rootReducers from '../reducers'; // where reducers is a object of reducers
import sagas from '../sagas';

const config = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: ['loginReducer'],
  timeout: 0, // The code base checks for falsy, so 0 disables
  debug: true, //to get useful logging
};

const middleware = [];
const sagaMiddleware = createSagaMiddleware();

middleware.push(sagaMiddleware);

if (__DEV__) {
  middleware.push(createLogger());
}

const reducers = persistCombineReducers(config, rootReducers);

const rootReducer = (state, action) => {
  if (action.type === 'LOG_OUT') {
    // for all keys defined in your persistConfig(s)
     Object.keys(state).forEach((key) => {
      AsyncStorage.removeItem(`persist:${key}`);
    });
    state = undefined;
  }
  return reducers(state, action);
};

const enhancers = [applyMiddleware(...middleware)];
const persistConfig = {enhancers};
const store = createStore(rootReducer, undefined, compose(...enhancers));
const persistor = persistStore(store, persistConfig, () => {
    console.log('Test', store.getState());
});
const configureStore = () => {
  return {persistor, store};
};

sagaMiddleware.run(sagas);

export default configureStore;
EricWiener commented 3 years ago

I think this is the same bug as described in https://github.com/rt2zz/redux-persist/issues/1294

asenmitrev commented 3 years ago

It seems redux-persist treats this use case as if initial state is being passed (you are really reusing the initialState logic when you clear the store this way). That is why it will not persist the changes to the reducer after undefined is passed in as state, since it is missing a _persist key in the state.

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.