Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    nader dabitnader dabit

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.