DEV Community

Cover image for How to handle multiple queries with React-Query
Calvin Torra
Calvin Torra

Posted on • Originally published at calvintorra.com

1

How to handle multiple queries with React-Query

There are two ways to handle multiple queries with React Query.

Method 1: Call useQuery Twice

The simplest method is just to call useQuery twice but re-assign the data variable that we're destructuring. They can't both be called data.

const { data: userData } = useQuery("users", fetchUsers);
const { data: postData } = useQuery("posts", fetchPosts);
Enter fullscreen mode Exit fullscreen mode

Method 2: useQueries

There is also useQueries which is perfect for this situation. It returns an array of queries. We can get access to each one using array destructuring.

const [posts, users] = useQueries([
    { queryKey: ["posts"], queryFn: fetchPosts },
    { queryKey: ["users"], queryFn: fetchUsers }
  ]);
Enter fullscreen mode Exit fullscreen mode

The queries that are returned from useQueries also contains the usual suspects like isLoading isError etc.

const [posts, users] = useQueries([
    { queryKey: ["posts"], queryFn: fetchPosts },
    { queryKey: ["users"], queryFn: fetchUsers }
  ]);

const { data, isLoading } = posts;
Enter fullscreen mode Exit fullscreen mode

There are also situations where you may want to wait for everything to finish before rendering any data. In that case, we can check if any / some of the queries are still in their loading state (isLoading comes from the useQuery hook).

  const results = useQueries([
    { queryKey: ["posts"], queryFn: fetchPosts },
    { queryKey: ["users"], queryFn: fetchUsers }
  ]);

  const isLoading = results.some((query) => query.isLoading);

  return { isLoading, results };
Enter fullscreen mode Exit fullscreen mode

Within our component, we only need to pull in 1 isLoading value and handle that case until ALL of the results are ready.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay