using multiple redux stores one for each app user

react-redux, reactjs, redux

Solution

Well Answer above work fine, but since i'm using ImmutableJs, having a deeply nested objects can really be hard to handle.

so i ended up namespacing the Storage Key with user_id.

so now when ever i switch user, i just flush the whole store with this specefic user data from localStorage, or AsyncStorage.

i wrapped rootReducer in a simple reducer to handle this.

function makeRootReducer(rootReducer){
 return function reducer(state, action){
   if(action.type==='SWITCH_USER'){
      //LOAD USER DATA..
      const data = JSON.parse(localStorage.getItem("store.user."+action.id)||"{}");
      return makeInitialData(data); //this just return initialData.
    }
    let newState = rootReducer(state, action);
    //simple save state to localStorage if state changed
    if(state !== newState)localStorage.setItem('store.user.'+state.user_id',JSON.stringify(newState);
    return newState;
  }

}

Problem

in a react native app, i'm using redux. currently the whole app have single store and i use redux-persist to cache store to localstorage. my app is username and password protected, you must create account to use it. now i want to provide ability so that my user can switch between his accounts -if he have more than one account- . this is causing lots of trouble because now i have to clear storage and reset state everytime user switch between accounts. so i was considering may be i can use multiple stores, one for every users ? for example my app state looks like ``` { chat:{}, highscores:{}, gameHistory:{}, } ``` now if a user have account lets say `User1@gmail.com` the state will be populated with his data. and his state will be saved to LocalStorage, once he switch account to `User2@gmail.com` now i have to reset the app to its initialState, then somehow load the User2 state from localStorage i dont want the state of the app to be lost everytime user switch between accounts. so i was considering may be in this case it would be a good option to use a multiple Redux Stores, one for every user. did anyone had an app that is designed to be used by multiple users before ? how can we do this in redux ?

Original source

Related problems