How to handle multiple queries with React-Query

A super cool feature of React Query is that we can execute multiple queries in the same component, whether these queries are dependent or independent of each other.

This article will demonstrate how we can execute multiple queries in the same component.


1- Multiple independent queries

React-Query comes with a hook called useQueries, This hook can be used to fetch a variable number of queries.

import React from 'react';
import { useQueries } from '@tanstack/react-query';
import axios from 'axios';

export default function Example() {
  const [postsQuery, usersQuery] = useQueries({
    queries: [
      {
        queryKey: ['posts'],
        queryFn: () =>
          axios
            .get('https://jsonplaceholder.typicode.com/posts')
            .then((res) => res.data),
      },

      {
        queryKey: ['users'],
        queryFn: () =>
          axios
            .get('https://jsonplaceholder.typicode.com/users')
            .then((res) => res.data),
      },
    ],
  });

  if (postsQuery.isLoading) return 'Loading Posts...';
  if (usersQuery.isLoading) return 'Loading Users...';

  if (postsQuery.error)
    return 'An error has occurred: ' + postsQuery.error.message;

  if (usersQuery.error)
    return 'An error has occurred: ' + usersQuery.error.message;

  return (
    <div>
      <h2>Posts</h2>
      {postsQuery.data?.slice(10).map((post) => {
        return (
          <div key={post.id} style={{ display: 'flex' }}>
            <span>{post.id}-&nbsp;</span>
            <div>{post.title}</div>
          </div>
        );
      })}

      <h2>Users</h2>
      {usersQuery.data?.map((user) => {
        return (
          <div key={user.id} style={{ display: 'flex' }}>
            <span>{user.id}-&nbsp;</span>
            <div>{user.name}</div>
          </div>
        );
      })}
    </div>
  );
}

In the above example does use the useQueries hooks, and we’ve defined two queries, the `posts`, and the `users` query.

For each query, we’ve defined a unique queryKey value, and a queryFn. The queryFn in each case will fire a request to an API that will return the lists of the posts and the users.

Then we’ve destructed both queries results from useQueries by `const [postsQuery, usersQuery]`.

At this stage, we can access any property from each query, such as `loading`, `error`, and `data`, and add the required logic to handle them.


2- Multiple dependent queries

There’s another approach from React-Query that allows us to execute multiple queries in the same component, The different here from the first option, is that the queries are dependent on each other, meaning the later query would only execute based on a certain conditions from the earlier query.

import React from 'react';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

export default function Example() {
  const {
    isLoading: loadingPost,
    error: errorPost,
    data: postData,
  } = useQuery(['post', 1], () =>
    axios
      .get('https://jsonplaceholder.typicode.com/posts/1')
      .then((res) => res.data)
  );

  const {
    isLoading: loadingPostComments,
    error: errorPostComments,
    data: commentsData,
  } = useQuery(
    ['comments', 'post', 1],
    () =>
      axios
        .get('https://jsonplaceholder.typicode.com/posts/1/comments')
        .then((res) => res.data),
    {
      enabled: postData && Object.keys(postData).length > 0,
    }
  );

  if (loadingPost) return 'Loading Posts...';
  if (errorPost) return 'An error has occurred: ' + errorPost.message;

  if (loadingPostComments) return 'Loading Comments...';
  if (errorPostComments)
    return 'An error has occurred: ' + errorPostComments.message;

  return (
    <div>
      <h2>Post</h2>
      {postData && (
        <div key={postData.id} style={{ display: 'flex' }}>
          <span>{postData.id}-&nbsp;</span>
          <div>{postData.title}</div>
        </div>
      )}

      <h2>-- Comments</h2>
      {commentsData?.map((comment) => {
        return (
          <div key={comment.id} style={{ display: 'flex' }}>
            <span>{comment.id}-&nbsp;</span>
            <div>{comment.body}</div>
          </div>
        );
      })}
    </div>
  );
}
In the example above, we’ve defined two dependent queries:
  1. Post with id=1 query.
  2. Comments that are related to post=1 query.

The only different in this example, is that we’ve added the enabled flag in the comments query as the following:

{
  enabled: postData && Object.keys(postData).length > 0,
}

Which means, the comments query won’t execute unless the post query is resolved to success and we’ve the postData are now available in the scope of the component.

How to handle multiple queries with React-Query
How to handle multiple queries with React-Query

Both examples can be found on StackBlitz.

Photo from Unsplash.

Related Posts

How to Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: