I've created a to-do list with local storage. If you create three list items and delete the second one, the deleted list item will reappear in place of the third item on refresh.
Edit: I'm not sure whether it's to do with local storage or with the original todo array. In the code below, I'm trying to remove the relevant value from the array, but I suspect this isn't working (logging the array to the console produces no result).
Although it has nothing to do with local storage, I think the issue lies with the following code:
function removeItem() {
let item = this.parentNode.parentNode;
let parent = item.parentNode;
let id = parent.id;
console.log(id)
let value = parent.textContent;
todo.splice(todo.indexOf(value, 1));
this.parentNode.parentNode.removeChild(this.parentNode);
saveTodos();
}
Edit: Here is the code I used to store the list items:
function saveTodos() {
let jsonstr = JSON.stringify(todo);
localStorage.setItem('todo', jsonstr);
}
function getTodos() {
localStorage.getItem('todo')
let jsonstr = localStorage.getItem("todo");
todo = JSON.parse(jsonstr);
if (!todo || !todo.length) {
todo = [];
}
else {
renderTodoList();
} }
Here is a link to the codepen: https://codepen.io/david-webb/pen/yLeqydK
Can you help?
This is because the current code seems to be removing the wrong item.
See scenario:
-> Remove item #2 ("t")
Output:
As you can see, the output shows
["t", "2"]
thought the localstorage array is["t", "1"]
.This is because of the flawed logic in the
removeItem
function.Try with this, instead.
fiddle: