3

How to handle multiple queries with React-Query

 1 year ago
source link: https://www.js-howto.com/how-to-handle-multiple-queries-with-react-query/
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.
neoserver,ios ssh client

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}- </span>
            <div>{post.title}</div>
          </div>
        );
      })}

      <h2>Users</h2>
      {usersQuery.data?.map((user) => {
        return (
          <div key={user.id} style={{ display: 'flex' }}>
            <span>{user.id}- </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}- </span>
          <div>{postData.title}</div>
        </div>
      )}

      <h2>-- Comments</h2>
      {commentsData?.map((comment) => {
        return (
          <div key={comment.id} style={{ display: 'flex' }}>
            <span>{comment.id}- </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.

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK