Outline
Right now, we're getting all of the habits and entries in one query. This is fine for such a small data set, but what if we had hundreds of habits with hundreds of entries? It might be nice to only get the entries when clicking a button instead of when the page renders.
We can do this using the useLazyQuery
hook that Apollo provides. This hook lets us run a query in response to an event like a button click instead of just when a component renders.
First, let's remove the entries from the habits query in App.js
:
// src/App.js
export const HABITS_QUERY = gql`
query HABITS_QUERY {
habits {
id
description
points
}
totalPoints {
points
totalCompletedEntries
}
}
`;
Then, we'll write our query for getting the entries separately based on the habit ID:
// src/Habit.js
export const ENTRIES_QUERY = gql`
query ENTRIES_QUERY($id: ID!) {
getEntriesByHabitId(id: $id) {
id
notes
completed
date
habitId
}
}
`;
Now we're ready for the useLazyQuery
hook. Let's import it at the top of Habit.js
:
// src/Habit.js
import { useMutation, gql, useLazyQuery } from "@apollo/client";
Then, add it underneath the rest of our hooks:
// src/Habit.js
const [loadEntries, { data: entriesData }] = useLazyQuery(ENTRIES_QUERY);
Notice that, just like with useMutation
, we're getting an array that contains a function and an object with data
, error
, and loading
. We're renaming data
to entriesData
to keep things clear and we're skipping error
and loading
since we've covered that in previous lessons.
Let's also create a variable to help us avoid null reference errors:
// src/Habit.js
const entries =
entriesData && entriesData.getEntriesByHabitId
? entriesData.getEntriesByHabitId
: [];
Be sure to swap out any references of habit.entries
with our new entries
variable like we do in the video.
Finally, we can create our button to load the entries:
// src/Habit.js
<button
className="blue-button"
type="button"
onClick={() => loadEntries({ variables: { id: habit.id } })}
>
Entries
</button>
If you check out the browser, you should be able to click the button and load the habit's entries on demand!