Sometimes, you don’t want to fetch data right away- but instead, you’d like to fetch data manually in response to some sort of event, like a button click!
In this quick article, I’ll show you how to use the useLazyQuery
hook to manually trigger client-side GraphQL queries.
Project setup & demo
We’re using Apollo Client 3 with React Hooks, and Trevor Blades’ Countries API.
You can find the entirety of the code in a Codesandbox here: https://codesandbox.io/s/apollo-client-uselazyquery-example-6ui35
Fetching data in response to a click event
Here’s the relevant code sample, we import useLazyQuery
from @apollo/client
, write a GET_COUNTRIES
query, and define the getCountries
function that we use to invoke the query.
// src/Countries.js
import React from "react";
import { useLazyQuery } from "@apollo/client";
import gql from "graphql-tag";
const GET_COUNTRIES = gql`
{
countries {
code
name
}
}
`;
export function DelayedCountries() {
const [
getCountries,
{ loading, data }
] = useLazyQuery(GET_COUNTRIES);
if (loading) return <p>Loading ...</p>;
if (data && data.countries) {
console.log(data.countries);
}
return (
<div>
<button onClick={() => getCountries()}>
Click me to print all countries!
</button>
{data &&
data.countries &&
data.countries.map((c, i) => <div key={i}>{c.name}</div>)
</div>
);
}
When the page first loads, it should look pretty empty as shown below.
![](https://apollographql.wpengine.com/wp-content/uploads/2020/03/1_NBiqrohkrkmi6bev_lj-bA-1024x734.png)
But when you click the button, it should run the GET_COUNTRIES
query and populate the data
variable with a countries
object containing the result of our query.
We can see that it worked because we’re presented with all the country names!
![](https://apollographql.wpengine.com/wp-content/uploads/2020/03/1_JCS5jHDcgnJOfIQJ8czOqg-1024x734.png)
That’s it! That’s how to execute queries manually with @apollo/client
.
—
For a more detailed explanation on how to use useLazyQuery
, check out the docs on Executing Queries Manually.