Heading back over to App.js, we've now created a new function editTask which calls setTasks with a map over tasks. This map will allow us to return the edited task into the array so that we'll be setting a new array onto our tasks which has the new edited value.

This function takes an argument editedTask which will be used to compare against the existing task through the id attribute. You can see we check editedTask.id === task.id. If we find the matching task, return a shallow copy of the task passed in by creating a new object and spreading the attributes over. ({ ...editedTask }).

To get this function to be used by our Task component, we'll pass it in through a new onSave prop on the Task. Inside Task, we'll use onSave in the saveEdit function. Now, when we click Save, we'll be updating our parent components tasks with the updated task name.

We also refactored Task props to have task as a prop instead of individual attributes. This allows us to more easily update the parent component by not having to declare individual attributes to update. We just call onSave({ ... task, name }) and we know that we're updating with the previously saved task object as it was passed into the component.

This sets us up to properly "Cancel" our task edit so we can revert to the original task name.

Your mission

Let's cancel the update. Implement cancel in Task.js.

Menu
Lesson 16/20
import { useState } from "react";
import styled from "styled-components";
// Importing shared components
import Header from "./Header";
import Subheader from "./Subheader";
import Button from "./Button";
import Task from "./Task";
import Card from "./Card";
import TasksContainer from "./TasksContainer";
// Importing data
import tasksData from "./tasks";

function uniqueId() {
  return Math.floor(Math.random() * 10000000);
}

export default function App() {
  const [tasks, setTasks] = useState(tasksData);

  function addTask() {
    setTasks([...tasks, { id: uniqueId(), name: "New task" }]);
  }

  function editTask(editedTask) {
    setTasks(
      tasks.map((task) => {
        if (editedTask.id === task.id) {
          return {
            ...editedTask,
          };
        }
        return task;
      })
    );
  }

  return (
    <Card>
      <Header> 🏴‍☠️ Captain's Tasks </Header>
      <Subheader> Manage the daily jobs at sea </Subheader>
      <Button onClick={addTask}>+ Add Task</Button>
      <TasksContainer>
        {tasks.map((task, i) => (
          <Task key={`task-${task.id}`} task={task} onSave={editTask} />
        ))}
      </TasksContainer>
    </Card>
  );
}