I am currently storing accessToken and user's info in local storage which is 'userInfo'
Where token will be stored in userInfo.token and userIno will be stored in userInfo.info
I want to update the token inside the userInfo and also want to keep userInfo.info unchanged, Is there any way to do this?
currently I am using this code:
localstorage.setItem('userInfo', data.token)
but it's deleting userInfo.info
userInfo structure:
{"token": eykjdbvksbkvsbks89all, "userinfo": {"email": [email protected]} }
CodePudding user response:
Try this Code example:
localStorage.setItem('userInfo',JSON.stringify({name:'reza',age:20}));
const data = window.localStorage.getItem('userInfo')
const newData = JSON.parse(data)
localStorage.setItem('userInfo',JSON.stringify({...newData,age:44}))
CodePudding user response:
You need to update the entire user
object in localStorage.
Example:
const user = {"token": "adkadjhk2h3hkhkhkh", "userinfo": {"email": ":[email protected]" } };
localStorage.setItem('userInfo', JSON.stringify(user))
const userInfo = JSON.parse(localStorage.getItem('userInfo'));
const newUpdatedUserInfo = {
...userInfo,
"token": "new-token-adkadjhk2h3hkhkhkh"
};
localStorage.setItem('userInfo', JSON.stringify(newUpdatedUserInfo))
CodePudding user response:
const userInfo = window.localStorage.getItem('userInfo')
const parsedUserInfo = JSON.parse(userInfo)
localStorage.setItem('userInfo', JSON.stringify({...parsedUserInfo,token: data.token }))
You can try this snippet.