Logic for Modifying Tasks
Explore how to write and test logic for modifying tasks in a React app. This lesson covers state handling for task completion, creating toggle handlers, and integration tests using Jest to ensure user interactions work as expected.
We'll cover the following...
Where we left off
In the previous exercise, we made the Task component forward user input to a callback function. Now, we will do the same for TaskList.
If you recall, we currently store tasks in state of the App component:
const [tasks, setTasks] = useState([]);
const handleNewTask = (task) => setTasks([...tasks, task]);
New handler functions
Do you notice anything off about the snippet above? When developing the Task component we decided to store tasks as a JS object like this:
{
label: 'Do this',
completed: false
}
We need to change the handleNewTask to account for that:
const handleNewTask = (task) => setTasks([...tasks, {completed: false, label: task}]);
We will also need a handler function to toggle the task as completed or not. Here is what I came up with:
const handleToggleTask = (taskIdx) => {
const newTasks = [...tasks];
newTasks[taskIdx] = {...newTasks[taskIdx], completed: !newTasks[taskIdx].completed};
setTasks(newTasks);
};
As you can see, this function accepts the task index as its argument. Then we go ahead and make a shallow copy ...