Dumping redux state on log out

When a user signs out of my mobile app and signs in as a different user, we need to make sure no application state can be carried over.

Adding a simple ‘LOGGED_OUT’ action that drops the application state is a straight forward solution. I’m keeping a few properties.

Here’s the normal reducers object that is exported.

var { combineReducers } = require('redux')

const reducers = combineReducers({
  attachments: require('./attachments'),
  user: require('./user'),
  //...etc
});

module.exports = reducers //or export default etc.

We can wrap the existing reducer with a single reducer that resets the state. Below, I’ve chosen to keep a few properties of my application state (out of about 20).

//existing reducers
const reducers = combineReducers({
  attachments: require('./attachments'),
  user: require('./user'),
  //...etc
});

//wrapped with the logged out action
const reducersWithLogoutDumpState = (state, action) => {
  if (action.type === 'LOGGED_OUT') {
    let newState = {}
    ['projects', 'device', 'user'].map(k => {
      newState[k] = state[k]
    })
    state = newState
  }
  return reducers(state, action)
}

module.exports = reducersWithLogoutDumpState

Here I’m creating a fresh state object (newState) and retaining the projects, device, and user properties from the old state.

Note that the export has changed to the new function name, so there’s no other changes throughout the application.

(An adaptation of the answer here: https://stackoverflow.com/questions/35622588/how-to-reset-the-state-of-a-redux-store.