Dave
Dave

Reputation: 2018

How can I store localStorage data in one object?

Now I got something like this, instead of creating new-info: {"name": "name", "description": "mydescription"} it deletes the previous new-info and just adds for example new-info: "test" How can I make this to be one object of values?

  function setName(value) {
      this.name = value
      localStorage.setItem('new-info', JSON.stringify(this.name))
    },
  function setDescription(value) {
      this.description = value
      localStorage.setItem('new-info', JSON.stringify(this.description))
    },

Upvotes: 0

Views: 30

Answers (1)

Bladeski
Bladeski

Reputation: 386

The issue appears to be that you are not assigning the required object to localStorage, but rather the string property, meaning you are overwriting the key new-info with a string. Try saving the entire object instead, like this:

const info = {
  name: '',
  description: ''
};

function setName(value) {
  info.name = value;
  saveToStorage();
};
function setDescription(value) {
  info.description = value;
  saveToStorage();
};
function saveToStorage() {
  localStorage.setItem('new-info', JSON.stringify(info));
}

Upvotes: 1

Related Questions