Member-only story
Easily make Parallel API Calls — React Query
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
andqueryFn
queryKey
— Should be unique and have the dependent variables used by API callsqueryFn
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 specsuseQueries
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