Become a member
to unlock all features

Level Up!

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


    Query GraphQL Data with Urql using React Hooks


    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.



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

    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.

    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.

    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.

    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.

    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.

    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.