Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a user is logged in and how to save their information? (React)

Tags:

reactjs

So pretty much I made a login page communicates with a backend to login a user. Now I want to take their data and store it for all my other components to know that there is

  1. A user logged in
  2. Have access to the user's information

I figured based on past StackOverflow answers, that the best way to do this is using JWT and LocalStorage. But all the answer's I've encountered seem to use Redux. I'm not using Redux at all for my application, and have no clue how to use it, so I was wondering if there's a way to do it without redux.

like image 566
adriam Avatar asked Dec 06 '17 22:12

adriam


People also ask

How do I track user activity on React?

react-tracking There are two ways to track user behavior in your site using this library: @decorator — Ejecting the app is the clean way to use decorators in create-react-app. Using useTracking hook — You need to install latest versions of React i.e 16.8. 0+ to use hooks.


1 Answers

You don't need Redux. You just have to store the JWT in localStorage. To do that, just use localStorage.setItem('token', data.token) when you receive the login success response from the API. It's that simple. You can read this article for more details. It's for React Redux applications but doesn't need Redux.

Then, assuming you are using react-router, you need two helper functions. The first will go on your protected routes and would look like this:

const requireAuth = (...) => {
  if(!localStorage.getItem('token')) {
    // go to login route
  }
  // stay on this route since the user is authenticated
}

The second goes on your unprotected routes and looks like this:

const verifyAuth = (...) => {
  if(localStorage.getItem('token')) {
    // go to your dashboard or home route
  }
  // stay on this route since the user is not authenticated
}

Keep in mind that you have to refresh the token according to the server expiration time. A good approach would be to create a call to the server asking if the token is still valid.

like image 168
Tiago Alves Avatar answered Oct 14 '22 01:10

Tiago Alves