Blog>
Snippets

Parallel Data Fetching with useQueries Hook

Showcase how to fetch multiple datasets in parallel using the useQueries hook from TanStack Ranger, handling the asynchronous tasks efficiently.
import { useQueries } from 'react-query';
import axios from 'axios';

const fetchData = () => {
  const results = useQueries([
    { queryKey: ['data1'], queryFn: () => axios.get('/api/data1').then(res => res.data) },
    { queryKey: ['data2'], queryFn: () => axios.get('/api/data2').then(res => res.data) },
    { queryKey: ['data3'], queryFn: () => axios.get('/api/data3').then(res => res.data) }
  ]);
  return results;
};
This function uses the useQueries hook from React-Query to fetch data from three different endpoints in parallel. Each query is represented by an object within the array passed to useQueries. The queryKey uniquely identifies the query, and the queryFn defines the function to fetch the data, using axios in this case. The results from useQueries are the query objects which can be used to access the status and data.