0

I have been writing some code that adds an item to a local storage array but have hit an issue where the array is not updated. As localStorage does not allow arrays, I have been converting to a string.

function addItem(add_item) {

    if (localStorage.getItem("list_items") === null) {
        localStorage.setItem("list_items", "");
    }
    else {
        "Something has gone horribly wrong!"
    }

    // Check if item is already added
    if(existingEntries == null) existingEntries = [];
    else {
        existingEntries = JSON.parse(localStorage.getItem("list_items"));
    }

    // Set entry to the currently selected item
    var entry = add_item;

    // Check if item is in string
    var exists = existingEntries.includes(entry);

    // Add item if it's not already in the array
    if (exists == false) {
        existingEntries.push(entry);
        localStorage.setItem("list_items", JSON.stringify(existingEntries));
    }
}

For some reason, the local storage is not being updated with the new value added on. Any ideas as to why? Thank you in advance.

2
  • Did you run that? There's a few errors in your console. Commented Apr 7, 2018 at 23:44
  • @DamienGold that would overwrite what is already there and not allow storing array Commented Apr 7, 2018 at 23:50

2 Answers 2

2

You have over complicated it.

Simplify this down to something like:

function addItem(add_item) {

  // parse existing storage key or string representation of empty array
  var existingEntries = JSON.parse(localStorage.getItem("list_items") || '[]');

  // Add item if it's not already in the array, then store array again
  if (!existingEntries.includes(add_item)) {
    existingEntries.push(add_item);
    localStorage.setItem("list_items", JSON.stringify(existingEntries));
  }else{
     // or tell user it's already there
     console.log(add_item + ' already exists')
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

So to delete I would do: if (existingEntries.includes(add_item)) { existingEntries.splice(add_item); localStorage.setItem("list_items", JSON.stringify(existingEntries)); }else{ }
you need to get the index of the item to use splice()
0

If your localstorage has data with a key 'list_items', localStorage.setItem("list_items", "my new data"); will overwrite the old data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.