Jazuly
Jazuly

Reputation: 1414

How to modify specify localstorage item in vuex?

I want to change specify localstorage item in vuex.

For example, I have localstorage item like this:

{
  'id' = 1, 'another' = 2
}

I want to change just id, how can I do this?

I just know the basic usage like this:

localStorage.setItem("user", JSON.stringify(state.currentUser))

I tried something like this but looks like its not working

localStorage.setItem("user.id", "2")

Upvotes: 0

Views: 1112

Answers (2)

D Malan
D Malan

Reputation: 11414

You can't exactly because localStorage stores everything as strings. Best is just to replace the entire object by JSON.stringify-ing the object again after modifying it.

So essentially:

// Get the user from localStorage and parse into object
let user = JSON.parse(localStorage.getItem("user"));
// Update an attribute on the user object
user.id = 2;
// Update the user in localStorage and stringify to string
localStorage.setItem("user", JSON.stringify(user));

Upvotes: 1

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You can use getItem() to get current value and spread operator to assign values as following:

const newValue = {
   ...JSON.parse(localStorage.getItem("user")),
   id: 2
}

localStorage.setItem("user", JSON.stringify(newValue))

Upvotes: 1

Related Questions