I am writing a logic to create a post and i want to add the logged in user as the user making the post, i have saved the refresh
token in my browser localstorage, when i copy the refresh token and paste in jwt.io, i get this response
{
"token_type": "refresh",
"exp": 1679234275085,
"iat": 1674953425085,
"jti": "d723e65f9bdctret41399e5d09278ef1fcbc",
"user_id": 1,
"username": "destiny",
"email": "[email protected]"
}
now how do i grab the user_id and use it in react, this is where i want to use it
const formData = new FormData()
formData.append("user", 1)
Instead of hardcoding the user_id as 1 or 2, i want to pass it in dynamically, how can i do this?
CodePudding user response:
You can use jwt-decode
library.
Install the
jwt-decode
library by runningnpm install jwt-decode
in your project's root directory.Import the library in your component or file where you want to use it:
import jwtDecode from 'jwt-decode';
Retrieve the JWT token from local storage:
const token = localStorage.getItem('refresh_token');
Decode the token and extract the
user_id
:const decoded = jwtDecode(token); const user_id = decoded.user_id;
Append the user_id to the form data:
formData.append("user", user_id)
Send the form data to your server to create the post.
Note:
- You should always validate the token and check the expiration date before using it.
- It's also important to check that the token exists in the local storage before using it, and handle the case where the token is not found.