Reputation: 27
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.
Upvotes: 0
Views: 1961
Reputation: 171698
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')
}
}
Upvotes: 2
Reputation: 1620
If your localstorage has data with a key 'list_items'
, localStorage.setItem("list_items", "my new data");
will overwrite the old data.
Upvotes: 0