🛠️ Todolist: Deleting tasks

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Todolist: Deleting tasks

When a user clicks on the delete button, we want to:

  1. Delete the task from the DOM
  2. Delete the task from the database

The API

To delete a task from the database, we need to send a DELETE request to the /tasks/:id endpoint. This means we need to know the task’s id to delete the task.

The task’s id is the id attribute in the task’s checkbox.

taskList.addEventListener('click', event => {
  // ...

  const taskElement = event.target.parentElement
  const checkbox = taskElement.querySelector('input[type="checkbox"]')
  const id = checkbox.id

  // ...
})

Once we have the task’s id, we can send a DELETE request.

If the DELETE request is successful, the server would respond with the deleted task.

taskList.addEventListener('click', event => {
  // ...

  zlFetch.delete(`${rootendpoint}/tasks/${id}`, { auth })
    .then(response => console.log(response.body))
    .catch(error => console.error(error))
})
Logged response from server.

Once we know the task is deleted from the server, we can safely delete it from the DOM as well.

taskList.addEventListener('click', event => {
  //...

  zlFetch(/* ... */)
    .then(response => {
      // Deletes Task from DOM
      taskList.removeChild(taskElement)

      // Triggers empty state
      if (taskList.children.length === 0) taskList.innerHTML = ''
    })
    .catch(error => console.error(error))
})
Deleted all tasks from the Todolist

That’s it!