2

I have been struggling from hours to solve this simple but tricky problem.

Am using react with redux. After user login into my application, i'll be having user object with fields like name profile_pic etc, am setting this to redux store and using those values where ever i want. It's working perfectly fine. But once page refresh/reload all redux state will rolled back to initial state.

To solve this am setting user object and authenticated flag in localStorage. I need to use this in home page component and all inner components.

But, getting from localStorage in all component lifecycle events will leads to code repetition.

I know, i can solve this by using libraries like redux-persist etc. But i don't want to use any libraries for this simple problem. Please sugest me a better way to do this. Thanks.

BTW - I tried following links, not worked/relevant for my case.
1. https://egghead.io/lessons/javascript-redux-persisting-the-state-to-the-local-storage
2.On React Router, how to stay logged in state even refresh the page?

2 Answers2

3

Every React application has an entry point; usually a script.js. When you refresh the page, this code always runs regardless of which component you are currently on. In this script, you likely also have access to your Redux Store due to configuration. In our application, we're just looking for the credentials in local storage and then dispatching that payload on the store.

const token = localStorage.getItem('token');
if (token) {
  const decoded = jwtDecode(token);
  store.dispatch({type: AUTH_USER, payload: decoded.scopes});
}

Your payload can be whatever you need it to be; this is just what we do.

Gregg
  • 34,973
  • 19
  • 109
  • 214
0

What you want to do is change a few things about the way you start up your redux store itself.

  • You will need to create a rehydrate function which takes localStorage and maps it into a shape your reducers can interact with. (I.E., it has to look like your state tree.)

  • You then need an inverted version of that function which serializes your state to a localStorage friendly shape (basically, a string). Ideally this function will debounce a bit because you're going to subscribe it to state changes, so it will get called a lot.

  • Finally, you want to invoke the rehydrate function as the second argument to createStore, then on the resulting store object, bind your debounced serializer function to store.subscribe.

Check out the API docs here for more information:

This is kind of a naive implementation, but it'll get you very far and maybe show you what some of those other tools you've looked at will do.

If you want to create a more advanced storage system, I think the next best spot to look will be the Redux middleware docs.

ironchamber
  • 204
  • 1
  • 10