Categories
React

Making HTTP Requests with React Query — Parallel and Dependent Queries

Spread the love

The React Query library lets us make HTTP requests easily in our React apps.

In this article, we’ll look at how to make HTTP requests with React Query.

Parallel Queries

Sometimes, we may want to make multiple GET requests concurrently.

To do this, we can add multiple useQuery hooks:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App";

const queryClient = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <StrictMode>
      <App />
    </StrictMode>
  </QueryClientProvider>,
  rootElement
);

App.js

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data } = useQuery({
    queryKey: ["todo", 1],
    queryFn: ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    }
  });
  const { data: yesNoData } = useQuery("yesNo", () =>
    axios("https://yesno.wtf/api")
  );

  return (
    <div>
      <div>{JSON.stringify(data)}</div>
      <div>{JSON.stringify(yesNoData)}</div>
    </div>
  );
}

We have useQuery hooks to make 2 requests in parallel.

Dynamic Parallel Queries with useQueries Hook

We can add dynamic parallel queries with the useQueries hook.

It returns an array of query results.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQueries } from "react-query";
export default function App() {
  const todos = useQueries(
    Array(5)
      .fill()
      .map((_, i) => i + 1)
      .map((id) => {
        return {
          queryKey: ["todo", id],
          queryFn: ({ queryKey: [, id] }) => {
            return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
          }
        };
      })
  );

  return (
    <div>
      <div>{JSON.stringify(todos)}</div>
    </div>
  );
}

We call useQueries with an array of query objects.

We call map to map the array of numbers we created with:

Array(5)
  .fill()
  .map((_, i) => i + 1)

to query objects.

And todos is an array of query objects.

Dependent Queries

We can make also make multiple HTTP requests where one depends on the other.

To do this, we write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data: id } = useQuery("id", () => Promise.resolve(1));

  const { data } = useQuery(
    ["todo", id],
    ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    },
    {
      enabled: Boolean(id)
    }
  );

  return (
    <div>
      <div>{JSON.stringify(data)}</div>
    </div>
  );
}

to make one query after the other.

We call the first useQuery hook to get an id for our todo.

Then we call useQuery again to pass in the id to the callback.

We set the enabled property to a boolean expression to indicate when we want to query to run.

We set it so that the 2nd query is run when id is truthy, which should only happen when we get the id from the first useQuery hook.

Conclusion

We can make parallel or sequential queries with React Query easily.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *