7. The useQuery hook
1m

The useQuery hook

The useQuery hook syntax, with variables
The useQuery hook syntax
useQuery hook
const {loading, error, data} = useQuery(A_GRAPHQL_QUERY);
useQuery hook, with variables
const {loading, error, data} = useQuery(A_GRAPHQL_QUERY, {
variables: {aVariable: 'the variable value'}
});

The gql tag

The gql tag
const A_GRAPHQL_QUERY = gql`
query ExampleQuery {
example
}
`;
const {loading, error, data} = useQuery(A_GRAPHQL_QUERY, {
variables: {aVariable: 'the variable value'}
});

Code-along: Display a list of tracks on the homepage

Goal: Display tracks on the homepage.

In the src/pages/tracks-home-page.js file, do the following:

  1. Import the gql and useQuery modules from @apollo/client.

    import {useQuery, gql} from '@apollo/client';
  2. Create a variable called GET_TRACKS_FOR_HOMEPAGE. We'll paste in the query we built earlier in Sandbox, making sure to wrap it in the gql tag.

    const GET_TRACKS_FOR_HOMEPAGE = gql`
    query GetTracksForHomepage {
    tracksForHome {
    id
    title
    thumbnail
    length
    modulesCount
    author {
    name
    photo
    }
    }
    }
    `;
  3. Inside the Tracks component, we'll use the useQuery hook, pulling out the loading, error and data properties from the return result.

    const Tracks = () => {
    const {loading, error, data} = useQuery(GET_TRACKS_FOR_HOMEPAGE);
    return <Layout grid>TODO: Replace me with real tracks!</Layout>;
    };
  4. We'll handle the loading state.

    if (loading) {
    return <Loading />;
    }
  5. Then handle the error state.

    if (error) {
    return <p>ERROR: {error.message}</p>;
    }
  6. Finally, we'll display the data when it's available. Inside the Layout component, we'll map over the data and display a TrackCard component for each track.

    if (data) {
    return (
    <Layout grid>
    {data.tracksForHome.map(track => (
    <TrackCard key={track.id} track={track} />
    ))}
    </Layout>
    );
    }
Previous
Next