Call the Create API
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.
We just need to use the API
module that AWS Amplify has.
Let’s include the API
module by adding the following to the header of src/containers/NewNote.js
.
import { API } from "aws-amplify";
And replace our handleSubmit
function with the following.
async function handleSubmit(event) {
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 });
props.history.push("/");
} catch (e) {
alert(e);
setIsLoading(false);
}
}
function createNote(note) {
return API.post("notes", "/notes", {
body: note
});
}
This does a couple of simple things.
-
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 theAPI.post()
method arenotes
and/notes
. This is because back in the Configure AWS Amplify chapter we called these set of APIs by the namenotes
. -
For now the note object is simply the content of the note. We are creating these notes without an attachment for now.
-
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.
Next let’s upload our file to S3 and add an attachment to our note.
For help and discussion
Comments on this chapterIf you liked this post, please subscribe to our newsletter, give us a star on GitHub, and follow us on Twitter.