📦 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.
When we click on TracksForHome
from our collection, the saved query is automatically inserted into a new tab in 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 {idtitlethumbnaillengthmodulesCountauthor {idnamephoto}}}`;
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
Our query is ready to execute. Let's finally display some catstronauts on our homepage!
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.