This video is available to students only

Persisting User Login

In this lesson, we're going to persist the login information

Persisting user login#

Although we see the user logged in, if we refresh the page, we will see login again. This is because Redux stores data in memory which removes it after a refresh. Now what we can do is; inside userSlice, we can create a new reducer function which will be called getUser. This function will just check if the token is still there inside localStorage. If it is, it will save it back to redux which will keep the user logged in. Let's create the reducer function now; const token is equal to localStorage.getItem which is user. Now we will check if the token exists, then we will store it to state dot user. To store it back, we will have to parse it back.

We can now export this function and use it inside App.tsx file. We will dispatch the getUser function. Before we go back to the browser, let's push the user to the profile page when they log in or register. Going back to the Signin component, let's use history which will be equal to useHistory provided by react-router-dom. Inside the try block, we can use history.push and push them to the profile page. Let's implement the same inside Register component, and let's use history equal to useHistory. Let's import it and finally use history.push, to the profile page.


Start a new discussion. All notification go to the author.