February 24, 2020

Apollo Client [React]— How to Query on Click

Khalil Stemmler
FrontendHow-to

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

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.

Similar posts

September 11, 2020

Announcing the GraphQL at Enterprise Scale Guide [Free Ebook]

by Michael Watson

Company