0

I want to update the dataId field of an object in localStorage. Object:

let responseJson = {
                      id: user.id,
                      username: user.username,
                      firstName: user.firstName,
                      dataId: 1000
                   };

I am tring using following code:

let loggedInUser = localStorage.getItem('user_id');
JSON.parse(loggedInUser).userId = parseInt(2000);
localStorage.setItem('user_id', loggedInUser);

Updated:

let loggedInUser = localStorage.getItem('user_id');
loggedInUser.dataId = parseInt(2000);
console.log('loggedInUser', JSON.stringify(loggedInUser));
localStorage.setItem('user_id', JSON.stringify(loggedInUser));
3
  • You need to JSON.stringify loggedInUser object when saving to localStorage Commented Jan 29, 2020 at 8:21
  • @HarunYilmaz Yeah I updated my code but still there is no value changed in localStorage Commented Jan 29, 2020 at 8:25
  • 1
    You're not modifying the loggedInUser value, you're modifying the parsed value, which is should be assigned to a variable, and then reencoded. Commented Jan 29, 2020 at 8:27

3 Answers 3

3

This can help:

let responseJson = {
                      id: user.id,
                      username: user.username,
                      firstName: user.firstName,
                      dataId: 1000
                   };

let loggedInUser = JSON.parse(localStorage.getItem('user_id'));
loggedInUser.dataId = parseInt(2000);
localStorage.setItem('user_id', JSON.stringify(loggedInUser));

enter image description here

Sign up to request clarification or add additional context in comments.

7 Comments

its not working
Hello @VarinderSohal, what are your getting an error?
can't assign to property "dataId" on {} : not an object
Can you update your code by sharing what you have currently?
Code update has done you can see it
|
1

In localStorage, all values must be of type string. So, you have to stringify your object before storing it.

localStorage.setItem('user_id', JSON.stringify(loggedInUser))

BTW: You should check the user_id value before parsing it (or encapsulate in a try/catch).

Comments

1

You can do something like this and you should stringify it before setting to localStorage:

let loggedInUser = JSON.parse(localStorage.getItem('user_id'));
let loggedInUserObj = {...loggedInUser, dataId : 2000}; // <---should be dataId
localStorage.setItem('user_id', JSON.stringify(loggedInUserObj));

Note:- You are not updating the dataId property but userId.

2 Comments

Thankyou for your reply but your code just added new field not updated current available filed.
@VarinderSohal oh yes. you should parse the string to object before and then destructure it to update. and one thing in your question you have posted to update the userId not dataId.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.