Execute Queries to an AWS AppSync GraphQL API from a React Application

nader dabit
Instructornader dabit

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson we’ll execute GraphQL queries using our AWS AppSync API and show how to display the returned data inside of our React application using the AWS AppSync GraphQL client.

We'll create a query string using gql (graphql-tag) and pass that query into a graphql Higher-order component where we will pass the resulting data in our exisiting app.

Instructor: [00:02] Now that we've configured our React application to connect to our AppSync API, let's go ahead and query for data and render it to our screen. To do so, open source/app.js.

[00:16] Here, we'll go ahead and import GQL from GraphQL tag as well as GraphQL and compose from React Apollo. Next, we'll define our query. The query that we're going to execute is listTodos, which will return an items array with an ID, a title and a completed value for every item in the array.

[00:59] Next, we'll scroll down and update our default export. Instead of exporting the app component, we're going to export the compose higher-order component, passing in app as the second function argument.

[01:13] For the first argument to compose, we're going to go ahead and pass in a GraphQL query of listTodos. The second argument to GraphQL will be an object containing an options object as well as a props object for any props we'd like to pass down to the component.

[01:31] For the options, we'll set a fetch policy of cache and network so that when the application loads, it will read first from the cache and then fetch data from the network. For the props, we'd like to pass down a prop of Todos, which will reset as an empty array if props.data.listTodos does not exist.

[01:48] If it does exist, we'll then pass down the props.data.listTodos.items array. Now, in our render method, we'll have access to this.props.todos. We'll map over the items in the Todos array, returning the item title for every item in the array.

[02:23] We should be able to test this out. Open your terminal and run npm start. If this is successful, you should see the Todo titles rendered to your screen.

Gribbs
Gribbs
~ 4 years ago

I had to yarn add graphql and apollo-client before I could get this lesson to work

Gribbs
Gribbs
~ 4 years ago

Actually, I meant to put this comment on lesson 5

Olivier
Olivier
~ 3 years ago

App is now a function, it would be great to refresh the tutorial

Michael Friedman
Michael Friedman
~ 3 years ago

I had to downgrade to app-sync 1.7.1 to get the list to render. Looks like there's a breaking change in the latest update.

Aaron Sturm
Aaron Sturm
~ 2 years ago

create-react-app now creates a functional component vs the class based in this video. To make this lesson work, add props as an argument to App function App(props) and remove this from this.props so that it's just props.todos.map.