Member-only story

Easily make Parallel API Calls — React Query

Vinodh Thangavel
1 min readJul 5, 2023

--

Parallel API calls are made for independent APIs , to avoid slow execution ,so their execution times don’t add up

With the help useQueries hook, we would achieve this easily


export default function App() {
const queries = [22, 10, 11, 1].map((todoId) => {
return {
queryKey: ['todo', todoId],
queryFn: () =>
fetch('https://jsonplaceholder.typicode.com/todos/' + todoId).then(
(response) => response.json()
),
};
});
const todos = useQueries(queries);

return (
<div>
{todos?.map(({ data }) => {
return <li key={data?.id}>{data?.title}</li>;
})}
</div>
);
}

Analysis

  • useQueries takes array of objects as an argument, each object must have two properties, queryKey and queryFn
  • queryKey — Should be unique and have the dependent variables used by API calls
  • queryFn should be responsible for making API call and should return a promise
  • [22, 10, 11, 1] array is mapped to array of objects as per above specs
  • useQueries will return an array of objects, which each object hold the metadata about that API and its data.
  • While accessing the data, ensure it is null checked with JS optional chaining

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet