Deleting Data
Let’s add the functionality to delete a task. We’ll start by defining a function to handle the deletion.
Code Explanation
- Before the
useEffect
hook we added thedeleteTask
function, which takes atask
as an argument. - The
taskRepo.delete
method deletes the given task. This makes a REST API call to the backend to delete the task from the database. - After deleting the task, we update the
tasks
state by filtering out the deleted task from the list. - If there’s an error, we display an alert with the error message.
- We kept the existing
useEffect
hook to fetch the tasks when the component mounts.
Next, let’s modify the JSX to call the deleteTask
function when the delete button is clicked.
Code Explanation
- We added a button with an
onClick
handler that calls thedeleteTask
function when the button is clicked. - The
onClick
handler passes thetask
to thedeleteTask
function.
This code results in the following REST API request to delete the task:
DELETE /api/tasks/{taskId}
Try deleting tasks using the delete buttons in the preview window below.
Files
Preparing Environment
- Installing dependencies
- Starting http server