9. Defining a query
2m

📦 A query in a component

Now that we've initialized Apollo Client, we can design the first query that our client will execute. Specifically, we'll design the query that our tracks page will use to display its card grid.

The code for our tracks page lives in src/pages/tracks.js. At the moment, the page just displays the bare layout that we've seen previously. Let's add a query definition to it.

Just like when we defined our schema, we need to wrap all GraphQL strings in the gql template literal. Let's import gql:

import {gql} from '@apollo/client';

Next we'll declare a constant called TRACKS with an empty GraphQL string (by convention, query constants are in ALL_CAPS):

export const TRACKS = gql`
# Query goes here
`;

Now, remember the query we built in the Apollo Studio Explorer to retrieve track data? Conveniently, that's exactly the query we need!

Head back to the Explorer, where the query is still available in the Operations panel (if it isn't, you can find previously executed queries in the Explorer's Run History tab). Copy the query.

copy query in apollo explorer

We can paste the query directly in our empty gql string. Let's add an export keyword to the declaration so the query is available in our test cases later on:

/** TRACKS query to retrieve all tracks */
export const TRACKS = gql`
query getTracks {
tracksForHome {
id
title
thumbnail
length
modulesCount
author {
name
photo
}
}
}
`;

Code Challenge!

Create a 'ListSpaceCats' query with a 'spaceCats' query field and its 'name', 'age' and 'missions' selection set in that order. For the 'missions' field, select 'name' and 'description'

Which of the following are best practices when creating client queries?

Our query is ready to execute. Let's finally display some catstronauts on our homepage!

Previous
Next