9. Defining a query
2m
You're currently on an older version of this course. View course changelog.

📦 A query in a component

Now that we've initialized , we can design the first 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 definition to it.

Just like when we defined our schema, we need to wrap all 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 string (by convention, constants are in ALL_CAPS):

const TRACKS = gql`
# Query goes here
`;

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

Head back to the Explorer, where we'll access the from our Sandbox collection.

http://localhost:4000
Screenshot of the Operation Collections menu, opened to access a saved operation

When we click on TracksForHome from our collection, the saved is automatically inserted into a new tab in the Operation panel.

http://localhost:4000
Clicking on an operation saved in a collection to insert it into the Operation panel

Let's copy the , and return to our code.

We can now paste the directly into our empty gql string.

/** TRACKS query to retrieve all tracks */
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 is ready to execute. Let's finally display some catstronauts on our homepage!

Previous

Share your questions and comments about this lesson

Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.