I want to get only accessToken value 123 inside Object in value in localStorage . I don't know how to get it.
key : stackoverflow
value :
{
"accessToken": "123",
"expiresAt": "2022-07-20T03:13:31.736756085Z",
"refreshToken": "456"
}
I've tried it myself and it doesn't work.
console.log(window.localStorage.getItem("stackoverflow", 'accessToken'))
Isn't this the way to get it?
The problem here is the value saved as json so you need to parse it first using JSON.parse() like this
let parsedData = JSON.parse(window.localStorage.getItem("stackoverflow"))
console.log(parsedData.accessToken)
You need to store the object as a JSON
// SET
localStorage.setItem('stackoverflow', JSON.stringify(stackoverflow));
Then get it and parse it
// GET
let stackoverflow = localStorage.getItem('stackoverflow');
stackoverflow = JSON.parse(stackoverflow);
And finally you can get the property of stackoverflow object
const accessToken = stackoverflow.accessToken;
Before saving the data, you must convert an object into a string, because localstorage only support string type, and whenever you want to get that object data, you must parse that data and then you can access object data
localStorage.setItem(
'stackoverflow',
JSON.stringify({
accessToken: '123',
expiresAt: '2022-07-20T03:13:31.736756085Z',
refreshToken: '456',
})
);
const stackoverflow: any = localStorage.getItem('stackoverflow');
const obj = JSON.parse(stackoverflow);
console.log(obj.accessToken);