⚠️ This lesson is retired and might contain outdated information.

Query GraphQL Data with Urql using React Hooks

Ian Jones
InstructorIan Jones
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 2 years ago

We use urql's useQuery to fetch data from a GraphQL endpoint. We look the result of the query, which gives us access to the queries status.

result.fetching will be true while the query is running. result.error will contain an error if the query returned an error. result.data will contain the data of our query to display to our user.

Instructor: [00:00] Here we have an app component that expects result. Right now, the result is NULL. We expect the result to have data.courses on it. Courses will be an array that we will map over. Each item in the array will have a title property.

[00:19] To start, let's import {useQuery} from 'urql'. Let's use useQuery and pass in a configuration object. Its configuration object expects query, and we'll call ours courseQuery.

[00:49] Up above, we'll define our query and it's just a string. Inside of our string we'll call it query courses. The egghead schema has course query defined, and we'll grab the title.

[01:16] We'll go over to our app and see it load, except none of the courses are showing up because useQuery passes an array back, and the first item on the array is the result. Now, the courses will load.

[01:40] There are a couple helper attributes that URQL gives us to know the state of the query. So if(result.fetching), if the result is fetching we can return loading. When we go to our app, we'll see the loading flash in the corner.

[02:07] Another attribute we can use is result.error. Error will show up when graphQL throws an error or our server throws an error, so will return "There was an error." Up here, we'll query for something that doesn't exist and graphQL breaks and we get our error message instead of a broken screen.

[02:50] To wrap up, we import useQuery from URQL, we call useQuery passing in our configuration object which expects query and our course query. We destructure the result off of useQuery. If the result is fetching, we return a loading state, if there's an error, we return an error. If everything went successfully and the data loaded, we map over courses and return the list of courses.