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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With