EmreSengul
EmreSengul

Reputation: 1

when i want delete to to-do-list from localStorage

when i want delete to to-do-list from localStorage i can delete from UI but i can't delete from localStorage

function deleteTodoFromStorage(deletetodo){
  let todos = getTodosFromStorage();

  todos.forEach(function(todo,index){
    console.log(todo,deletetodo,index)
    if (todo === deletetodo){
        todos.splice(index,1);
        console.log("Test");
    } 
  });

  localStorage.setItem("todos",JSON.stringify(todos));
}

Upvotes: 0

Views: 148

Answers (2)

Devashish
Devashish

Reputation: 1290

This will solve your problem:

function deleteTodoFromStorage(todoToRemove) {
localStorage.setItem(
    "todos",
    JSON.stringify(
        JSON.parse(localStorage.getItem("todos")).filter(todoItem => {
            return todoItem !== todoToRemove;
        })
    )
);
}

deleteTodoFromStorage("buy milk"); // or anything else

Upvotes: 0

Long Tran thanh
Long Tran thanh

Reputation: 86

You should not call forEach on todos and splice itself inside callbacks (which may causes index changing). I suggest you to use filter method instead.

newTodos = todos.filter(todo => todo !== deletetodo) 
localStorage.setItem("todos",JSON.stringify(newTodos))

Upvotes: 1

Related Questions