Query Multiple Services with urqls GraphQL Client in React

Ian Jones
InstructorIan Jones

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 4 months ago

In this lesson, we install urql to use as our GraphQL client. urql provides us with some utilities to provide our GraphQL client through React Context.

We use urqls useQuery hook to pass a GraphQL query to. Then we log the results to the console.

Instructor: [0:00] The first thing we're going to do is run npx create-react-app subscriptionApp. Now that that's finished, we're going to see the subscriptionApp. We'll open it in our editor. We'll close the side panel with CommandB, and we'll open the terminal with Control+backtick.

[0:27] The first thing we want to do is yarn add URQL and yarn add GraphQL. Now that that's done, we'll close our terminal. We'll open our file nav and head over to index.js. Here, we're going to delete some things that we don't need up at the top. We will import createClient and provider from URQL.

[1:03] Next, we're going to create the client that URQL uses, so const client createClient. CreateClient takes a configuration object, and one of the options is URL. This the URL of our GraphQL server. It's the one that we just made in OneGraph.

[1:23] If we head over to our browser, we go to the home tab. We will need this GraphQL endpoint, we can copy it and paste it in here. I like to make a variable so I'll go const client URL equals. We'll pull this out.

[1:49] The next thing we need to do is use our provider to pass the client anywhere we need inside of our application. We'll go provider, and then provider takes a value prop. We will pass our client as the value.

[2:13] Inside app.js we can import useQuery from URQL. We'll make a variable called Query. It's going to be a template literal. We'll go back to OneGraph and grab this query. I believe that this needs too.

[2:47] Now that we have our query, we'll use our useQuery hook, so const useQuery returns an array, just like useState. useQuery takes a object to configure it. Inside of this object, it takes a parameter of query, and that's when we'll pass our query in. The two things that use query return are the result and the preExecuteQuery function.

[3:25] Let's take a look at what the result of a query is, so console.log result. We will need to go back to our terminal and run yarn start. It starts the development server.

[3:40] Let's head over to our browser. We'll open the developer tools. Here, we can see we're getting a bunch of log statements. Look at the first one. The first time we log the result, fetching is true, stale is false, and there's no data. Second time, still no data, still no data, so on.

[4:05] Then, finally, in our result, fetching is false and our data is returned. When we look in here, we can see the same exact result that we got from our GraphQL editor is now inside our React app.