Become a member
to unlock all features

Level Up!

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


    Send a GraphQL Query with Apollo Client


    Apollo Client allows you to build performant, production-ready applications that consume data from GraphQL services. In this lesson, we will query the totalDays field using Apollo Client.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: I'm going to start off by installing two packages, the Apollo Boost and GraphQL. Then we'll come over to our source file and we will import the Apollo Client and a function called GQL from Apollo Boost. Now we can create an instance of the Apollo Client by using the Apollo Client Constructor.

    When we create our client, we'll have to tell it where to send the network request. Instead of using the endpoint, I'm going to rename this to URI because the Apollo Client requires a field called URI.

    In order to send a query using the Apollo Client, we must first parse it into an abstract syntax tree. That's what this GQL function does. Now we're ready to send our query. I'll start by logging a message to the console, letting our users know that we're sending the query.

    Now we can use the query method on the Apollo Client to send the query. When we receive a response from our GraphQL service that response will be parsed as JSON and then passed back to this next-then function.

    Then I can destructure the data field from that response and use it to create my total day string. We can go ahead and just log that string to the console. If any errors occur, we will catch them and log them using console error.

    Now I'll open the terminal and run our client by typing npm-start. We can see our app running on localhost-3000, and we can see our sending the query message along with the value for total days that we received from the GraphQL service.

    Let's take a closer look at what's going on here. The Apollo Client is responsible for handling all network requests. That's why we sent the URI to the client when we created it. Additionally, the Apollo Client also caches all of our queries locally.

    We can take a look at the cache at any point simply by typing client.cache.extract. When I log the extracted cache, we can see that we have an object here where our results were saved under the field, root query.