How to retreive one information from a localStorage key?

Viewed 43

Is it possible to retreive one information from a localStorage key ?

I have a key containing for example various information about the user after a connection :

{"id":1,"email":"AnEmail@Gmail.com","roles":SimpleUser,"iat":SomeNumber,"exp":SomeNumber}

And one of my axios request is : passing the user id in the URL, like this :

export const getAllOfSomething = (userId) => axios.get(`${URL}/something/${userId}`,
{
    userId: userId,
});

Probably a stupid question but I'm still learning everything

EDIT : I store my key like this when a connection is good :

const handleSubmit = event => {
        event.preventDefault();
        login(event.target.email.value, event.target.password.value).then(response => {
            const Token = response.data.accessToken;
            localStorage.setItem('UserToken', Token);
            User = jwt_decode(Token)
            localStorage.setItem('User', JSON.stringify(User))
             history.push({
                  pathname: '/',
             });
            window.location.reload(false);

        }).catch(err => {
            setErrorForm(err.response.data.message);
        });
    };

The first localStorage.setitem is to only store the JWT Token.

The seconde one, I decode this Token to retrieve all the information about the user and this is what i get in my localStorage after decode :

enter image description here

1 Answers

Is it possible to retreive one information from a localStorage key ? The answer is yes, you can retrieve what's being stored.

Here's an example of storing an object :

localStorage.setItem(key, JSON.stringify(object));

And that's how to retrieve it :

JSON.parse(localStorage.getItem(key));

Here's also a functional example :

public static store(object: any, key: string) {
if (object === null || object === undefined) {
  return -1;
} if (key === null || key === undefined) {
  return -2;
}else {
  localStorage.setItem(key, JSON.stringify(object));
  return 1;
}

public static retrieve(key:string){
if (key === null || key === undefined) {
  return null;
}
return JSON.parse(localStorage.getItem(key));

}

Related