hancho
hancho

Reputation: 1437

Reseting the redux store/state when a User Logs Out

I'm making a fitness app and running into an issue that I do not think will be too hard to fix, but I have been stuck.

When User 1 logouts, and user 2 logs in, user 2 will have user 1s workout log until they refresh the page. This is because the state isn't clearing the workout log when logging out.

I tried to fix this in my sessionsReducer, but haven't succeeded.

My idea with the if conditional was to pass back an empty state if currentUser is null. Null is passed back with my logout thunk action.

I wasn't sure what other action creator I could make to help fix this problem.

My reducer and logout is below.

import merge from 'lodash/merge';

import { RECEIVE_CURRENT_USER, RECEIVE_ERRORS } from '../actions/session_actions'

const nullUser = Object.freeze({
  currentUser: null,
  errors: []
});


const sessionReducer = (state = nullUser, action) => {
  Object.freeze(state);
  let newState;

  switch(action.type) {
    case RECEIVE_CURRENT_USER:
      if (action.currentUser === null) {
        newState = merge({}, {});
     } else {
       newState = merge({}, state);
     }
      const currentUser = action.currentUser;
      return merge({}, newState, {
        currentUser
      });
   case RECEIVE_ERRORS:
     const errors = action.errors;
     return merge({}, nullUser, {
        errors
     });
   default:
     return state;
  }
}

 export default sessionReducer;

Thunk action creator.

export const logout = () => (dispatch) => {
  return APIUtil.logout().then(() => dispatch(receiveCurrentUser(null)),
    err => dispatch(receiveErrors(err.responseJSON)));
};

Upvotes: 0

Views: 2214

Answers (1)

mradziwon
mradziwon

Reputation: 1236

To clear store after logout I usually do something like:

const createReducer = () => {
  const reducer = combineReducers({
    app: appReducer,
    // rest of your reducers
  });
  return (state, action) => {
    if (action.type === 'SIGN_OUT') {
      state = undefined;
    }
    return reducer(state, action);
  };
};

You can read more about cleaning store problem here.

Upvotes: 2

Related Questions