Search code examples
javascriptreactjsreduxredux-middleware

Simple way to access localStorage instead of redux-store


I just exported a few things from my store to the localStorage (actual logged in user) so the user should be able to open a second tab without login again.

For putting data in the localStorage i used a Redux-Middleware (if action is login I put the login data in the localStorage).

export const storageMiddleware = () => next => action => {
    console.log("Share Middleware...");
    console.log(action);
    switch(action.type){
      case 'LOGIN':
        localStorage.setItem('login-token', action.token);
        localStorage.setItem('login-token-expiration', action.expiration);
        break;
      default:
        break;
    }
    next(action);
  };

Now my question: Is there a simple way to get the data from the localStorage? Like a read middleware where I call localStorage.getItem instead of returning the value from the redux store?

Or do I have to change every component which uses the login-data to access the localStorage instead of the redux store.

Now I access the token via mapStateToProps-method.


Solution

  • One of simple way to do this is the use redux-persist, it persist the redux state to local storage. Also there is option to blacklist or white-list the specific reducers. By using this package, we don't have to manually handle local storage as the redux store updates