February 24, 2020

Apollo Client [React]— How to Query on Click

Khalil Stemmler
Developer Advocate
@stemmlerjs
Last updated May 19, 2021

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.

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

Follow

Developer Advocate at Apollo GraphQL ⚡ Author of solidbook.io ⚡ Advanced TypeScript & DDD at khalilstemmler.com

Read more by Khalil Stemmler

Stay in our orbit!

Become an Apollo insider and get first access to new features, best practices, and community events. Oh, and no junk mail. Ever.

Make this article better!

Was this post helpful? Have suggestions? Consider so we can improve it for future readers ✨.

Similar posts

January 31, 2024

What’s new in Apollo Client 3.9

by Alessia Bellisario

Company