Send a GraphQL Query with Apollo Client

Alex Banks
InstructorAlex Banks
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

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.

Instructor: [00:00] 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.

[00:21] 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.

[00:32] 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.

[00:50] 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.

[01:03] 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.

[01:19] 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.

[01:34] 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.

[01:50] 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.

Srinivas  Kasiriveni
Srinivas Kasiriveni
~ 5 years ago

where can i get the code ?

Rob Wetherall
Rob Wetherall
~ 5 years ago

I'm getting this error: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist, but http://localhost:4000 is up and running and I get the correct response on GraphQL playground. What do I do about this?

Markdown supported.
Become a member to join the discussionEnroll Today