February 24, 2020

Apollo Client [React]— How to Query on Click

Khalil Stemmler

Khalil Stemmler

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.

1// src/Countries.js2import React from "react";3import { useLazyQuery } from "@apollo/client";4import gql from "graphql-tag";56const GET_COUNTRIES = gql`7  { 8    countries {9      code10      name11   }12  }13`;1415export function DelayedCountries() {16  const [17    getCountries, 18    { loading, data }19  ] = useLazyQuery(GET_COUNTRIES);2021  if (loading) return <p>Loading ...</p>;22  if (data && data.countries) {23    console.log(data.countries);24  }2526  return (27    <div>28      <button onClick={() => getCountries()}>29        Click me to print all countries!30      </button>31      {data &&32        data.countries &&33        data.countries.map((c, i) => <div key={i}>{c.name}</div>)34    </div>35  );36}

When the page first loads, it should look pretty empty as shown below.

A page with a button that, when pressed, will invoke a query.

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!

A mapped list of countries fetched after calling the GET_COUNTRIES query in response to a button click.

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.

Written by

Khalil Stemmler

Khalil Stemmler

Read more by Khalil Stemmler