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.