0

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);
  }
}
3
  • This might help you. Commented Nov 21, 2022 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) Commented Nov 21, 2022 at 20:53
  • Does this answer your question? adding objects to array in localStorage Commented Aug 28, 2023 at 11:21

1 Answer 1

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))
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.