9. Defining a query2m

📦 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):

const TRACKS = gql`
# Query goes here

Now, remember the query 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 query from our Sandbox operation collection.

Screenshot of the Operation Collections menu, opened to access a saved operation

When we click on TracksForHome from our collection, the saved query is automatically inserted into the Operation panel.

Clicking on an operation saved in a collection to insert it into the Operation panel

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

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

/** TRACKS query to retrieve all tracks */
const TRACKS = gql`
query GetTracks {
tracksForHome {
author {
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!