Here's a function i'm having trouble with the foreach loop traverses just fine but i'm having trouble removing item from localStorage.
function removeFromLocalStorage(taskItem) {
let tasks;
if (localStorage.getItem("tasks") === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem("tasks"));
}
tasks.forEach((task, index) => {
if (task === taskItem) {
tasks = localStorage.removeItem(task);
}
});
}
try this
function removeFromLocalStorage(taskItem) {
let tasks;
if (localStorage.getItem("tasks") === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem("tasks"));
}
let result = tasks.filter(task => task != taskItem);
localStorage.setItem('tasks', JSON.stringify(result));
}
Looks like you are trying to remove an element in the array that you have stored in localstroage.
You have to remove the element from the array and then set it back
function removeFromLocalStorage(taskItem) {
// gets the array from the localstorage
let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
// removing the taskItem by filter method and setting it back
localStorage.setItem("tasks", tasks.filter(task => task !== taskItem));
}