-1

I wanted to save data in local storage in form of array. the first item is adding successfully but when i try to ad second item it replace item 1

this is my script file

function store(title, description) {
  let titl = JSON.parse(localStorage.getItem("titl"));
  let descriptio = JSON.parse(localStorage.getItem("descriptio"));

  if (titl == null) {
    t = [title];
    localStorage.setItem("titl", JSON.stringify(t));
  } else {
    t = [title]
    titl.push(t);
  }

  if (descriptio == null) {
    d = [description];
    localStorage.setItem("descriptio", JSON.stringify(d));

  } else {
    d = [description];
    titl.push(d);
  }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • [This](https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage) might help you. – c0m1t Nov 21 '22 at 20:06
  • `titl` is (should be) an array, you can just `titl.push(description)` unless you want an extra dimension to your array? (same for descriptio) – NickSlash Nov 21 '22 at 20:53
  • Does this answer your question? [adding objects to array in localStorage](https://stackoverflow.com/questions/19635077/adding-objects-to-array-in-localstorage) – AztecCodes Aug 28 '23 at 11:21

1 Answers1

1

You do not update LocalStorage for the second value and you are pushing an array with a value into an array.

I think you just want to push a value into the array? From what I understood the following code should solve your issue.

The Code:

function store(title, description) {
    // Load the existing values (default to an empty array if not exist) 
    let _title = JSON.parse(localStorage.getItem("title") || "[]")
    let _description = JSON.parse(localStorage.getItem("description") || "[]")

    // Add the new items
    _title.push(title)
    _description.push(description)

    // update stored values
    localStorage.setItem("title", JSON.stringify(_title))
    localStorage.setItem("description", JSON.stringify(_description))
}
NickSlash
  • 4,758
  • 3
  • 21
  • 38