Updating Data
Let’s add the functionality to update a task’s completion status. We’ll start by defining a function to handle the update.
async function setCompleted(task: Task, completed: boolean) { const updatedTask = await taskRepo.update(task, { completed }) setTasks(tasks.map((t) => (t.id === updatedTask.id ? updatedTask : t)))}useEffect(() => { taskRepo.find().then(setTasks)}, [])Code Explanation
- Before the
useEffecthook we added thesetCompletedfunction, which takes ataskand acompletedstatus as arguments. - The
taskRepo.updatemethod updates thecompletedstatus of the given task. This makes a REST API call to the backend to update the task in the database. - After updating the task, we update the
tasksstate with the updated task, replacing the old task in the list.
Next, let’s modify the JSX to call the setCompleted function when the checkbox is toggled.
{ tasks.map((task) => { return ( <div key={task.id}> <input type="checkbox" checked={task.completed} onChange={(e) => setCompleted(task, e.target.checked)} /> {task.title} </div> ) })}Code Explanation
- We added an
onChangehandler to the checkbox input that calls thesetCompletedfunction when the checkbox is toggled. - The
onChangehandler passes thetaskand the newcheckedstatus of the checkbox to thesetCompletedfunction.
This code results in the following REST API request to update the task:
PUT /api/tasks/{taskId}
Try toggling the completion status of tasks using the checkboxes in the preview window below.
Files
Preparing Environment
- Installing dependencies
- Starting http server