Skip to content

Joey Ng'ethe

Using React-Query with Graphql

React, Graphql1 min read

In this post, we will look at how you can use react-query with a graphql based API.

By the end, you will be able to;

  • Install, and set up react-query.
  • Send a graphql request using the fetch API.
  • Use react-query to fetch data from a graphql API
  • Fetch some graphql jobs listing and display them

Before we get started, you will need to have a react app that you will use. I will use an app bootstrapped with CRA in this tutorial, but you can use any React application; Nexjs, Gatsby, CRA, etc.

Let's get started

Installing react-query and setting it up

We will install react-query by running;

1$ yarn add react-query

Next, we need need to wrap our app with QueryClientProvider and provide a queryClient instance

1// index.js file
2
3import { StrictMode } from "react";
4import ReactDOM from "react-dom";
5
6import { QueryClient, QueryClientProvider } from "react-query";
7import App from "./App";
8
9const queryClient = new QueryClient();
10
11const rootElement = document.getElementById("root");
12ReactDOM.render(
13 <StrictMode>
14 <QueryClientProvider client={queryClient}>
15 <App />
16 </QueryClientProvider>
17 </StrictMode>,
18 rootElement
19);

And with that, our app is now ready to use ReactQuery's hooks.

Making a Graphql request using fetch

We will use the open graphql jobs APIas our backend, and to make the request, we will use the fetch API.

Below is a signature function of making a graphql request using fetch, accepting a query, making the request, and returning the data.

1const fetchData = async (query) => {
2 /* pass in a query string e.g
3 const query = `
4 query queryName{
5 ...
6 }
7 `
8 */
9 const API_URL = "https://api.graphql.jobs/"; // <-- your graphql API url
10 const res = await fetch(API_URL, {
11 method: "POST",
12 headers: { "Content-Type": "application/json" },
13 body: JSON.stringify({
14 query,
15 }),
16 });
17 const data = await res.json();
18 return data;
19};

Let's define a query string as below;

1const GRAPHQL_JOBS_QUERY = `
2 query JobsQuery{
3 jobs{
4 id
5 title
6 description
7 }
8 }
9`;

We will then modify our fetchData function slightly to return the correct data key as below;

1..
2 return data.data.jobs
3 ..

Using react-query to make a Graphql request

We will first import useQuery from react-query

1import { useQuery } from "use-query";

We can then pass our function to react-query's use-query hook.

1const { data: jobs = [], isLoading, isError } = useQuery(
2 "graphql-jobs",
3 async () => fetchData(GRAPHQL_JOBS_QUERY)
4);

We can then render some UI from the values we use-query gives us back.

1function App() {
2 const { data: jobs = [], isLoading, isError } = useQuery(
3 "graphql-jobs",
4 async () => fetchData(GRAPHQL_JOBS_QUERY)
5 );
6 return (
7 <div className="App">
8 <h1>Graphql Jobs</h1>
9 {isLoading && <p>Fetching jobs...</p>}
10 {isError && <p>:( failed to fetch graphql jobs</p>}
11 <ul>
12 {jobs.map(({ id, title, description }) => (
13 <li key={id}>
14 <h3>{title}</h3>
15 <p>{description}</p>
16 </li>
17 ))}
18 </ul>
19 </div>
20 );
21}

And with that, we have a simple app that fetches graphql jobs and displays them with the benefits that react-query offers, among them being;

  • Caching
  • Deduping multiple requests for the same data into a single request
  • Updating out of date data in the background
  • Knowing when data is stale.
  • Reflecting updates to data as quickly as possible
  • Performance optimizations like pagination and lazy loading data
  • Managing memory and garbage collection of server state
  • Memoizing query results with structural sharing
What next?

If you are new to react-query, I highly suggest going through its docs and examples. It does offer a lot more than what I have shown on here.

If you are getting started with graphql, I'd recommend going through the how-to graphql tutorial.

After going through the above resources, the best way to better grasp what you learn is by building something. So go ahead and build something.
Happy coding