Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i get the user_id from jwt in the localstorage and use it in react?

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": "desphixs111@mailnator.123"
}

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use jwt-decode library.

  1. Install the jwt-decode library by running npm install jwt-decode in your project’s root directory.

  2. Import the library in your component or file where you want to use it:

    import jwtDecode from 'jwt-decode';
    
  3. Retrieve the JWT token from local storage:

    const token = localStorage.getItem('refresh_token');
    
  4. Decode the token and extract the user_id:

    const decoded = jwtDecode(token);
    const user_id = decoded.user_id;
    
  5. Append the user_id to the form data:

    formData.append("user", user_id)
    
  6. 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading