I don’t know how to extract only a specific value from my JWT token, I use react-jwt as my React library to decode my token, when I console.log I get this:
Object { userId: "850dff98-54fb-4059-9e95-e44f5c30be0f", iat: 1698866016 }
And I’d like to extract only the value of userId to put it in a localstorage like this: localStorage.setItem("userId", "the value")
import {useJwt} from "react-jwt"
export async function JWTDecode() {
const token = localStorage.getItem("token")
const { decodedToken } = useJwt(token!);
console.log(decodedToken)
}
2
Answers
You have to parse the string with JSON.parse first, then you can access the members.
You should probably also add some error handling and validation in there to make sure the token object is valid.
Also, you could type it as they suggested in the Github Issue
Had to reference the attributes using
?
but that should be fine,Sandbox here