How to Build a CRUD App with Amplify and AWS AppSync

How to perform CRUD operations with the database by using GraphQL mutations

Krissanawat Kaewsanmuang
Oct 5 · 11 min read

AWS Amplify is a framework that lets us develop a web or mobile application quickly. In this tutorial, we are going to continue to learn how to perform CRUD operations with the database by using GraphQL mutations. AWS Amplify has a complete toolchain wiring and managing APIs with GraphQL. The API we will be creating in this tutorial is a GraphQL API using AWS AppSync (a managed GraphQL service) and the database will be Amazon DynamoDB (a NoSQL database).

Image for post
Image for post

Please before you begin this tutorial to follow the part 1 where we discussed the setting up Amplify as a framework as well as email authentication with custom UI.

Create a GraphQL API

To start creating an API and connect the database run the below command in a terminal window.

Image for post
Image for post

This CLI execution automatically does a couple of things. First, it creates a fully functional GraphQL API including data sources, resolvers with basic schema structure for queries, mutations, and subscriptions. It also downloads client-side code and configuration files that are required in order to run these operations by sending requests. The above command will prompt us to choose between what type of API we want to write in. Enter a profile API name. In the below case, we are leaving the profile name to default.

Image for post
Image for post

Next, it will again give us two options as to how we want to authenticate the AWS AppSync API. In a real-time application, we have different users accessing the database and making requests to it. Choose the option Amazon Cognito User Pool. This is a more pragmatic approach. Since we have already configured Amazon Cognito User Pool with the authentication module, we do not have to configure it here.

Image for post
Image for post

For the next two questions Do you want to configure advanced settings for the GraphQL API and Do you have an annotated GraphQL schema? the answer is N or no. Amplify comes with pre-defined schemas that can be changed later.

When prompted Choose a schema template, select the option Single object with fields.

Image for post
Image for post

Before we proceed, let’s edit the GraphQL schema created by this process. Go to the React Native project, and from the root directory, open the file amplify/backed/api/[API_NAME]/schema.graphql.

The default model created by the AppSync is the following:

Currently, a warning must have prompted when finished the process in the CLI that is described as:

Since we have the authentication module already enabled we can add the@authdirective in the schema.graphql file. By default, enabling owner authorization allows any signed-in user to create records.

If you’re not familiar with GraphQL models and its types here’s a brief overview.

A typein a GraphQL schema is a piece of data that's stored in the database. Each type can have a different set of fields. Think of the typeas an object coming from the JavaScript background. For example, in the above schema for the Todomodel is the type that has three fields: id, nameand description. Also, the@model directive is used for storing types in Amazon DynamoDB. This is the database used by Amazon when storing our app data.

The exclamation mark!signifies that the field is required when storing the data and it must have a value. In the above schema, there are two required fields: idand name for the Todo type.

Save this file and all the changes we have just made are now saved locally.

Publish API to AWS Cloud

On running the command, as a prompt, it returns a table with information about resources that we have used and modified or enabled. The name of these resources is described in the Category section.

The Resource name in the above table is the API name chosen in the previous section.

Image for post
Image for post

The Amplify CLI interface will now check for the schema and then compile it for any errors before publishing final changes to the cloud.

In the next step, it prompts us to choose whether we want to generate code for the newly created GraphQL API. Press Y. Then choose JavaScript as the code generation language.

Image for post
Image for post

Press Y to the next question that asks to update all GraphQL related operations. Also, let maximum statement depth be the default value of 2. It will take a few moments to update the resources on the AWS cloud and will prompt with a success message when done.

Image for post
Image for post

Adding an Input Field in the React Native App

To capture the user input, we are going to use two state variables using React hook useState. The first state variable is for the name namefield of the todo item and an array called todos. This array will be used to fetch all the todo items from the GraphQL API and display the items on the UI.

Next, import TextInputand TouchableOpacityfrom React Native to create an input field and pressable button with some custom styling defined in StyleSheetreference object below the Homecomponent. Here's the complete code for Home.js:

Make sure you are running the expo startcommand in a terminal window to see the results of this step.

Image for post
Image for post

Adding a Mutation using the GraphQL API

A mutation in GraphQL is all about handling operations like adding, deleting, or modifying data. Currently, the React Native application is basic, but it serves the purpose of making you familiar with Amplify as a toolchain and its integration with the cross-platform framework.

To add an item and to retrieve the same in the React Native app, let’s add some business logic to communicate with the GraphQL backend with a mutation.

This is done by Amplify and to use any of the above mutations, we can directly import the method in the component file. In Home.js file, import API and graphqlOperation from the package aws-amplify. The API is the category for AWS resource and the second function imported is the method to run either a mutation or the query. Also, import the mutation createTodo from graphql/mutation.js file.

Let’s add the logic inside the addTodo custom handler method we defined in the previous section. It's going to be an asynchronous function to fetch the result from the mutation and update the todos array. It takes name as the input where name is the text of the item.

Before we move on to the next section, try adding some data.

Running a Query to Fetch the Data from AWS AppSync

To fetch the data from the database we need to run a query. Similar to mutations, Amplify also takes care of creating initial queries based on GraphQL schema generated.

All the available queries can be found in the src/graphql/queries.js.

To fetch all the data from the GraphQL API and display it on the device’s screen, let’s use the query from the file above. Import listTodosinside Home.js file:

To fetch the data from the database, let’s use the useEffect hook. Make sure to import it form React library:

Let’s define another handler method called fetchTodos to fetch the data by running the query listTodos. It is going to be an asynchronous method, so let's use the try/catch block to catch any initial errors when fetching data. Add the following code snippet inside the Home component:

The array of data returned from the database looks like the following:

Image for post
Image for post

Also, update the corresponding styles:

Here is the result you are going to get:

Image for post
Image for post

Add a Loading Indicator while the Query is Fetching Data

Right now the when the app is refreshed, or when the user logs in, it takes time to make the network call to load the data, and hence, there is a slight delay in rendering list items. Let’s add a loading indicator using ActivityIndicator from React Native.

To know when to display the loading indicator when the query is running, let’s add a new state variable called loadingwith an initial value of boolean falsein the Homecomponent. When fetching the data, initially this value is going to be true, and only when the data is fetched from the API, its value is again set to false.

Here is the output:

Image for post
Image for post

Running the Delete Mutation to Delete an Item\

To delete an item from the todos array the mutation deleteTodo needs to be executed. Let's add a button on the UI using a TouchableOpacity and @expo/vector-icons to each item in the list. In the Home.js component file, start by importing the icon and the mutation.

Then, define a handler method called removeTodo that will delete the todo item from the todos array as well as update the array by using the filter method on it. The input for the mutation this time is going to be the id of the todo item.

Now, add the button where the todo list items are being rendered.

Here is the output you are going to get after this step.

Image for post
Image for post

Summary

On completing this tutorial you can observe how simple it is to get started to create a GraphQL API with AWS AppSync and Amplify.

At Instamobile, we are building ready to use React Native apps, backed by various backends, such as AWS Amplify or Firebase, in order to help developers make their own mobile apps much more quickly.

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

Originally published at https://www.instamobile.io on October 5, 2020.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store