Step 21: Add Notes

Let’s reuse the Edit view for writing new notes!

First, we update the add function in the App.jsx as follows:

const add = () => {
  const note = {
    id: faker.datatype.uuid(),
    title: "New note title",
    text: "New note text",
  };

  setNotes((notes) => [...notes, note]);

  return note;
};

Next, update the handleOnClick function in the components/Header.jsx as follows:

const handleOnClick = () => {
  const { id, title, text } = add();
  navigate("/edit", { state: { id, title, text } });
};

Observe how the “Add Note” feature works now:

Let’s address a subtle issue: when we click on “Add Note” button, a new note is created first, and then we are redirected to “edit” its title and text. What if we click on the “Cancel” button?

So the “cancel” button does not “undo” adding a new note. It only “cancels” editing the newly created note. If it is desired to cancel “adding a new note,” we can remove the newly created note before redirecting the user to the homepage.

First, pass the remove function to the Edit component in App.jsx:

- <Route path="/edit" element={<Edit edit={edit} />} />
+ <Route path="/edit" element={<Edit edit={edit} remove={remove} />} />

Next, update the handleOnClick function in components/Header.jsx as follows:

  const handleOnClick = () => {
    const { id, title, text } = add();
-   navigate("/edit", { state: { id, title, text } });
+   navigate("/edit", { state: { id, title, text, mode: "remove-on-cancel" } });
  }

Finally, update the pages/Edit.jsx as follows:

  function Edit(props) {
-   const { edit } = props;
+   const { edit, remove } = props;

	
    const handleCancel = () => {
+     if (mode === "remove-on-cancel") {
+       remove(id);
+     }
      navigate("/", { replace: true });
    };
	
    return (
      <Container>
        <Stack spacing="lg">
          <TextInput
            placeholder="Your note's title"
            label="Title"
            withAsterisk
            value={title}
            onChange={handleTitleChange}
          />
          <Textarea
            placeholder="Your note's text"
            label="Text"
            withAsterisk
            autosize
            minRows={5}
            value={text}
            onChange={handleTextChange}
          />
          <Group position="center" spacing="xl" grow>
            <Button variant="subtle" onClick={handleCancel}>
             Cancel
            </Button>
            <Button variant="default" onClick={handleSave}>
             Save
            </Button>
          </Group>
        </Stack>
      </Container>
    );
  }
	
  export default Edit;
	
  Edit.propTypes = {
    edit: PropTypes.func.isRequired,
+   remove: PropTypes.func.isRequired,
  };

Observe how the “cancel” for “Add Note” feature works now: