Now that we have our basic create note form working, let’s connect it to our API. We’ll do the upload to S3 a little bit later. Our APIs are secured using AWS IAM and Cognito User Pool is our authentication provider. Thankfully, Amplify takes care of this for us by using the logged in user’s session.

Define the type for a note

Let’s start by creating a type definition for the note object. Create a new directory for our types.

Change indicator Run the following in the packages/frontend/ directory.

$ mkdir src/types

Change indicator Add a new file src/types/note.ts with the following.

export interface NoteType {
  noteId?: string;
  content: string;
  createdAt?: string;
  attachment?: string;
  attachmentURL?: string;
}

Call the Create API

Change indicator Next, we’ll replace our handleSubmit function in src/containers/NewNote.tsx with.

function createNote(note: NoteType) {
  return API.post("notes", "/notes", {
    body: note,
  });
}

async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault();

  if (file.current && file.current.size > config.MAX_ATTACHMENT_SIZE) {
    alert(
      `Please pick a file smaller than ${
        config.MAX_ATTACHMENT_SIZE / 1000000
      } MB.`
    );
    return;
  }

  setIsLoading(true);

  try {
    await createNote({ content });
    nav("/");
  } catch (e) {
    onError(e);
    setIsLoading(false);
  }
}

Change indicator And include the API module by adding the following to the header of src/containers/NewNote.tsx.

import { API } from "aws-amplify";
import { NoteType } from "../types/note";
import { onError } from "../lib/errorLib";

We are doing a couple of things with these functions.

  1. We make our create call in createNote by making a POST request to /notes and passing in our note object. Notice that the first two arguments to the API.post() method are notes and /notes. This is because back in the Configure AWS Amplify chapter we called these set of APIs by the name notes.

  2. For now the note object is simply the content of the note. We are creating these notes without an attachment for now.

  3. Finally, after the note is created we redirect to our homepage.

And that’s it; if you switch over to your browser and try submitting your form, it should successfully navigate over to our homepage.

New note created screenshot

Next let’s upload our file to S3 and add an attachment to our note.