'I'm having trouble removing an item from localStorage for my tasklist app which i'm building using vanilla javascript
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);
}
});
}
Solution 1:[1]
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));
}
Solution 2:[2]
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));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Abhishek |