jack
jack

Reputation: 100

Clear the redux store after logout

I have created a redux store below, the only thing I want to clear the redux store when user logout from the application, so store having the latest and updated data of currently logged user.

import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import rootReducer from './Reducers';
import { sessionService } from 'redux-react-session';
import thunk from 'redux-thunk';

const persistedReducer = persistReducer({ key: 'root', storage }, rootReducer);

const composeEnhancers =
  (typeof window !== 'undefined' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
  compose;

export const store = createStore(
  persistedReducer,
  composeEnhancers(
    applyMiddleware(thunk)
  )
);
export const persistor = persistStore(store);
sessionService.initSessionService(store);

The above snippet I wrote to create the store using redux persist please suggest

Upvotes: 3

Views: 6406

Answers (2)

shrikantbishoye
shrikantbishoye

Reputation: 979

import { persistor } from './store'

const handleLogout = () => {
  dispatch({ type: 'LOGOUT' })
  persistor.purge();
}

Upvotes: 0

Engazan
Engazan

Reputation: 525

you need to modify your rootReducer that u pass to persistReducer, where you put some action like RESET

code example (from your code)

import rootReducer from './Reducers';

const appReducer = (state, action) => {
  if (action.type === 'RESET') {
    return rootReducer(undefined, action)
  }

  return rootReducer(state, action)
}

const persistedReducer = persistReducer({ key: 'root', storage }, appReducer);

then you need to call that RESET action somewhere like that

store.dispatch({type: "RESET"})

store is from your configureStore or what you pass to Provider tag from react-redux, also persisted storage will be cleared too

Upvotes: 0

Related Questions