Search code examples
javascriptvue.jslocal-storagevuex

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

Solution

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