Home > Enterprise >  Saving user data in redux but not in localStroage
Saving user data in redux but not in localStroage

Time:06-17

I have user data which includes Email,Username,Password,ShippingAddress etc.. I am storing jwt token in localStorage, the token is includes :username,id,createdAt..

I want the user data to be persisted to my redux-store but I can't figure out how to do it.

I don't want user info to be in local storage but on the other hand everytime I refresh the page my user data from redux getting deleted, I kinda stuck. Tried to do simple check that if localstorage(jwt) id is equal to the user that just logged in - store the data in store and it works, but as I said one refresh delete all..

Would like to get some hints\tips from the pros! :)

Using: graphql\apollo, redux toolkit, react.

My best idea was to have requests from the server on every component that I need username \ email \ password ..etc but I think it will be too massy..

CodePudding user response:

React is just JavaScript, and as such, any data that is stored in React will not persist and will be lost when the page is refreshed. Any information that you want to persist after a page refresh will need to be stored somewhere else (i.e. local storage).

There are ways to retrieve information from local storage and store them (non-permanently) in Redux after every page reload. How that solution looks will differ depending on how you are using React.

If you are using functional components and hooks, the useEffect hook can be used to retrieve data from localStorage after every page reload. Click here to read the docs on useEffect. It might look something like this:

useEffect(() => {
    const storedData = JSON.parse(localStorage.getItem("storedData"));
    // save to component's state or redux here.
  }, []);

If that useEffect is placed somewhere in your app component, it will run on every re-render, thereby making it seem like the data is persisting in React because it will always be there.

CodePudding user response:

Normally the flow that you would have should be smth like:

  • User logs in e.g /api/v1/login,
  • Sever returns either a temporal token (in case you are using otp codes or 2fa), or the user jwt that will be used for authorizing subsequent requests.
  • Token is saved in local storage.
  • When the user refreshes the page you check local storage and use the token on a request to the server (this way you can check it's still valid, normally you can do smth like /api/v1/user to get the user data.
  • If the token is valid then you can store the user info returned by the API call into the redux store. If not you can redirect user to login page again
  • Related