简体   繁体   中英

How to remove a specific item from a Local Storage array?

I'm building a To Do List (codepen) app and I am stuck on removing a specific item from Local Storage. I feel like I have the right code, but It's not working. Here's an overview:

Adding a few tasks sets those tasks in Local Storage. I'm trying to remove that task item when a user clicks the green "checkmark" on that task:

Here's my completeDelete function that moves the task into the "completed" category, and tries to remove that task from Local Storage:

const completeDelete = (e) => {
  let checks = results.querySelectorAll(".fa-check"); //Checkmark
  let deletes = results.querySelectorAll(".fa-times");

  //Complete Task:
  checks.forEach((check) => {
    
    if (e.target === check) {
      let closestTask = check.closest(".task"); //The task element
      let taskText = closestTask.firstElementChild.textContent; //the task text, to be removed
      
      closestTask.remove();
      
      removeTaskFromLS(taskText); //The function that removes the task:
      
   }

Here's the Remove Task function:


const removeTaskFromLS = (task) => {
  let storedTasks = JSON.parse(localStorage.getItem("tasks"));
  const i = storedTasks.indexOf(task);
  if (i > -1) {
    let newArr = storedTasks.splice(i, 1);
    localStorage.removeItem(JSON.stringify(task)); //not removing from Local Storage
    console.log(task);
  }
  console.log(storedTasks);
};

If I put the following tasks in: Task 1 Task 2 Task 3

And check complete on Task 1, I'm left with an array of ["Task 2", "Task 3"]. But Local Storage is unaffected, and loads fully with a reload. What am I doing wrong? Thanks in advance.

JSON.parse(localStorage.getItem("tasks")) will give you string instead of Array. Use split post parsing and you will get Array.

 const removeTaskFromLS = (task) => { let storedTasks = JSON.parse(localStorage.getItem("tasks")).split(","); const i = storedTasks.indexOf(task); if (i > -1) { let newArr = storedTasks.splice(i, 1); localStorage.removeItem(JSON.stringify(task)); //not removing from Local Storage console.log(task); } console.log(storedTasks); };

It appears like the "tasks" key contains an array of tasks, and you appear to splice it off the parsed array correctly. However, you'll need to persist that spliced array back into localStorage to replace the old one.

Replace the line containing removeItem with:

localStorage.setItem('tasks', JSON.stringify(storedTasks));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM