This is the stuff that you would do a lot in a CRUD application.
First, we will update the tasks variable to use state, which in React is done with the useState hook.
useState returns an array with two items:
- The current value of the state
- A function to update the state
const tasks = [{ id: 1, taskName: 'First Task' }];
const [tasks, setTasks] = React.useState([{ id: 1, taskName: 'First Task' }]);Next, we will wire up the addTask function:
const addTask = (task) => {
// Write the logic
const trimmedTask = task.trim();
if (!trimmedTask) {
return;
}
const newTask = {
id: Math.random().toString(36).substr(2, 9),
taskName: trimmedTask,
};
setTasks([...tasks, newTask]);
};We check if the task is empty before we add it. If it is empty, we do not add the task and return. Otherwise, we create a new task object with a unique ID and the trimmed task name.
Then we use the setTasks function to update the tasks state with the new task. We use the spread operator to create a new array with the new task added.
Finally, we can wire up the deleteTask function:
const deleteTask = (id) => {
// Write the logic
setTasks(tasks.filter((task) => task.id !== id));
};We filter the tasks array to remove the task with the matching ID and create a new array without the deleted task. Then we use the setTasks function to update the tasks state with the new array.
Bonus Task
How do we add a clear all tasks feature?
const clearAllTasks = () => {
setTasks([]);
};We use the setTasks function to update the tasks state with an empty array to clear all tasks.
Next, we just have to link the function to a UI element. We will create a button that calls the clearAllTasks function with some basic styling.
<button
onClick={clearAllTasks}
className="border border-red-500 bg-red-500 p-2 text-white"
>
Clear All
</button>