Veera Silamban
Veera Silamban

Reputation: 297

How to update particular element of local storage in reactjs

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]} }

Upvotes: 1

Views: 2217

Answers (3)

Frank Mendez
Frank Mendez

Reputation: 572

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.

Upvotes: 1

Reza Ghorbani
Reza Ghorbani

Reputation: 537

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}))

Upvotes: 2

Asif vora
Asif vora

Reputation: 3347

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))

Upvotes: 2

Related Questions