

How to Fire an Event-Driven GraphQL Query with Apollo Client for React
source link: https://spin.atomicobject.com/2022/01/26/graphql-query-apollo/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Fire an Event-Driven GraphQL Query with Apollo Client for React
If you’re building an application that uses React and GraphQL, then the Apollo Client library provides useful hooks that help manage the flow of your application’s data. A popular use-case of Apollo Client is the useQuery
hook, which makes a GraphQL query when a React component renders. However, many applications require the ability to fire a GraphQL query when an event occurs (such as a button click), rather than a component render. For this situation, look no further than Apollo Client’s useLazyQuery
hook.
useLazyQuery vs. useQuery
Unlike useQuery
, useLazyQuery
does not immediately execute its associated query upon component render. Rather, the hook returns a 2-tuple. The tuple contains a function that can be called in an event callback, and a result object, respectfully. The result object is similar to that returned by useQuery
. If you’ve never used Apollo Client, that result object will contain the following properties (among others):
loading: boolean
(Checks if the query resolution is currently in progress)error: ApolloError | undefined
(Provides information if the query resolution failed)data: any
(Provides an object in the shape of the query definition)
An Example: Dog vs. Cat Picture
Furthermore, useLazyQuery
comes in handy if you don’t know what your arguments will be upon component render. Let’s go through an example that demonstrates this situation. Suppose we have a basic user interface that displays a picture of a dog or cat depending on a user’s button click.
import React from 'react';
const App: React.FC<{}> = () => {
return (
<>
<img src={/* TODO - get from GraphQL */ undefined} />
<button>
Dog!
</button>
<button>
Cat!
</button>
</>
);
}
Additionally, suppose that we’ve written a GraphQL query and resolver that takes a simple string argument and returns a corresponding image based on whether the input reads “Dog” or “Cat.”
const GET_PET_PHOTO = gql`
query GetPetPhoto($choice: String!) {
pet(choice: $choice) {
id
imageURL
}
}
`;
Finally, leveraging useLazyQuery
and the above GraphQL query, we’re able to finish writing the component. getPet
is the function called in each button’s event callback. And, { loading, error, data }
represents a destructured version of the result object that changes based on the state of the query.
import React from 'react';
import { useLazyQuery } from '@apollo/client';
const App: React.FC<{}> = () => {
const [getPet, { loading, error, data }] = useLazyQuery(GET_PET_PHOTO);
if (loading) return <p>Loading ...</p>;
if (error) return `Error: ${error.message}`;
return (
<>
{data?.pet && <img src={data.pet.imageURL} />}
<button onClick={() => getPet({ variables: { choice: ‘Dog’ } })}>
Dog!
</button>
<button onClick={() => getPet({ variables: { choice: ‘Cat’ } })}>
Cat!
</button>
</>
);
}
Fire an Event-Driven GraphQL Query with Apollo Client for React
That’s it! The query function can be called by any callback in your React application. For more information on Apollo Client, feel free to explore the documentation here.
Recommend
-
70
这篇文章主要介绍 GraphQL 在 Client 的使用,为了方便,本文会直接使用 React 创建一个 Web demo 去介绍 Apollo 在 React 中的使用方法,当然在 ReactNative 中用法几乎一模一样。 Apol...
-
9
A/B Testing Using React, GraphQL and Apollo By Ryan Sydnor, ...
-
12
If you’re integrating your React frontend with a GraphQL API, you may want to check out the Apollo client! I found it to be pretty straightforward to hook up. In this post, we’ll create a React project from scratch using create-r...
-
7
When I learn a new technology, the first thing I think is “okay, how do I use this?” But soon thereafter, the question becomes “how do I test this?” That was the case recently with Apollo GraphQL in my React project. In this post, we’l...
-
12
JavaScript
-
13
React Server Side Rendering Using GraphQL and apollo A baseline for server side rendering for your React application using GraphQL Apollo. Inspired by https://github.com/manuelb...
-
4
Testing GraphQL Queries with Apollo ClientIn this blog post, we are going to learn how to test our GraphQL operations on an Apollo client in a React application.Quality means doing it right whe...
-
5
Integrating third-party APIs into GraphQL with Apollo ClientTo add fast and feature-rich third-party APIs into any codebase, developers need to work within an ecosystem designed...
-
10
-
5
Apollo Client with GraphQL In this post, we will explore Apollo Client integrated with a React application and how it provides an abstraction layer between a JavaScript application and a GraphQL server. The features...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK