react redux state changed to initial after browser refresh - reactjs

I am making a react app using redux. I am going great except one issue.
Whenever I refresh the browser my state changed to initial state. Lets say I have a user authenticated and I have set him as authenticated: true and after authenticating when I refresh the page the state changed to initial and authenticated:false is set.
I am confused why is this happening ?
Can anyone point what might be the issue here

Redux stores are not persistent. When the page reloads, all data is initialized again. If you would like to save a piece of your store (or the whole thing) you will need to save it in localstorage, or saving it to your server and making a REST request asking for the data again.
You can use this package to save your store into localstorage.

Related

Saving user data in redux but not in localStroage

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..
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.
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

React problem routing : no need re-rendering on second time

I’m making a simple app with react-routing component.When user enter in /config path, it open a configuration page where he can choose element from select.
After this, user save data and the application set state of main component correctly (App.js). Then i make a “view change” using history to return in home (/ path).
The problem is : if user click on second time in /config routes, it lose all previous change made on DOM and it seems to be a new istance.
How i can preserve user interaction after first change? I cannot understand if i need to make a state inside this (Config.js) or there are an alternative solution.
Thanks for all
If you have an app level configuration which should be preserved between renders/navigation you should consider using some sort of a state management like Redux or you should store your config inside sessionStorage/localStorage (sessionStorage keeps track only while your browser tab is active = not closed. localStorage saves for the future when user closes and reopens your app).
Learn more about Web Storage API on how to use sessionStorage and localStorage.
NOTE: When you navigate away from your component, it gets unmounted which means that the component's state is destroyed/trashed. That's probably the situation you're facing now with your project.
You need to store the data/state/config somewhere. If it's just a few things (nothing heavy or complex), you can use localStorage (it saves the data between sessions, doesn't matter if you close tab and open it again)... But if you need to have a greater control over the app's state you should consider diving into Redux Store.
Have in mind that by default redux doesn't support data persistence so you'll need to plug-in Redux Persist package to achieve that (it's like saving in localStorage, but now the whole Redux (with all the states) will be saved between sessions)
I am not sure what you mean by
lose all previous change made on DOM
Where do you store these changes made and could you not check for this state and render the contents of the /config component or even the component itself depending on whether or not the changes to the state have been made?

Persisting redux state vs dynamic urls

In the app I am working on I have a state that is chosen in a dropdown by the user. I would like this state to still be the same after the user refreshes the page
Two options:
Store the state in the url by adding "/:state"
We must hit the api endpoint again to get the data based on the state. So it is always fresh
The url can be stored in history and copied/bookmarked
Everytime the state is changed by the user, the url changes causing a reload of the page
Store the state in redux and persist it
Have to install a package like redux-persist which takes some configuration
data persists on page reload so we don't need another api call
data may be outdated and need to be re-pulled
Which option is better? What scenarios break either option?
Everytime the state is changed by the user, the url changes causing a reload of the page
If you use something like react-router, app doesn't reload each time you change url.
Decision where to store some setting depends on the case. I usually prefer to store in url only things that are related to navigation: changing views/pages, opened modals, search/filters. Usually you want to store it in url when you want this url to be shareable with other users. So it you want to put some dropdown value in url, consider: Do you want browser navigation to change this value? Does this dropdown change some view?
Also, sometimes you have to store this selection on backend. Usually when it is a property of some entity or it's a setting. You have to consider whether you want this dropdown's value to be shared between multiple sessions on different devices.

How to make render still remained after reload?

The problem that I'm facing now is, there's a profile tab which shows some information on itself. I typed interface solutions like "input". After I save its value to data(data that placed on another component, especially contained in this.state). Then I shifted to component which renders its interface. In detail, I mentioned its value to which to show. Soooooo, I can't understand that how to still show it after reload? I hope it pulls something from back-end or axios or git things. Briefly, "how to maintain the data on the profile tab after reload? I'm in react js stuff.
React state is just a variable which stores data. When you refresh your browser, the browser clears its value from memory and reinitilizes that variable.
To get back that data, you have to store that data somewhere which persists even after browser refreshes like
You can use session Storage or local storage.
https://javascript.info/localstorage
You can user server to store your data and use axios to fetch data using useEffect hook.
You can also use the npm package redux-persist or react-persist https://www.npmjs.com/package/redux-persist

React save global state before page refresh

I'm using React to build an website where the user needs to login.
The website keeps states from the user.
This is the state of auth.
This state isn't changed much.
When I refresh the page my state gets refreshed too!
I want to keep the state if someone refreshes the page.
I looked at: https://hackernoon.com/how-to-take-advantage-of-local-storage-in-your-react-projects-a895f2b2d3f2 but that is only for states in current page only.
I want to save the main state of the app no matter on what page the user is on when page is refreshed.
How to do that?
I don't know what code you guys need, so ask me and Ill add it to the question.
I really need help with this.
You can save your state in localstorage using redux-persist. It will also update localstorage when redux state will be updated and persist when page reloaded

Resources