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

后端 未结 1 1265
梦如初夏
梦如初夏 2021-02-04 15:57

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条回答
  • 2021-02-04 16:28

    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.

    0 讨论(0)
提交回复
热议问题