Access a property of a saved object in localstorage

Asked

Viewed 139 times

1

After logging in, I saved a user’s id and token to my localStorage via a currentUser-named object.

How can I access the id and token property of this object when recovering from localStorage?

What I tried to:

var USUARIO = localStorage.getItem('currentUser')
const TOKEN = JSON.parse(USUARIO.id);
const CLIENT_ID = JSON.parse(USUARIO.token);

but I get:

"Property 'id' does not exist on type 'string'"

Is there any way to retrieve this object and assign it to token and client_id?

  • has already inspected the USER variable to see how it is, if it has the property?

  • I think in the arrows has to pass as an object, like localStorage.setItem('valores', JSON.stringify(object));

  • 1

    getItem returns a string, then the way to turn it into a user will depend on how it was recorded there. Assuming it was recorded as a JSON, just do JSON.parse(localStorage.getItem('currentUser')) - and then you don’t need to call the parse when picking up the id and token

1 answer

2


Error hints: the variable USUARIO is a string. You must convert it before:

var USUARIO = JSON.parse(localStorage.getItem('currentUser'));
const TOKEN = USUARIO.id;
const CLIENT_ID = USUARIO.token;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.