https://tanstack.com/query/v3/docs/react/reference/useQueries
https://www.js-howto.com/how-to-handle-multiple-queries-with-react-query/
The useQueries hook can be used to fetch a variable number of queries
Usage in YelpCamp:
// Camground index
const [campgroundQuery, favoritedCampgroundsQuery] = **useQueries**([
{
queryKey: ['campgroundData'],
queryFn: () => axios.get(`/api/v1/campgrounds/${campgroundId}`).then(res => res.data),
onSuccess: (data: Campground) => {
document.title = `YelpCamp | ${data.title}`;
setCampground(data); // setting campground specifically to ensure new data
},
onError: err => {
appContext.setAlert({
message: 'Invalid campground!',
variant: 'warning',
});
navigate('/');
},
},
{
queryKey: ['favoritedCampgrounds'],
queryFn: () =>
axios
.get(
`/api/v1/users/${appContext.currentUser.id.toString()}/favorited-campgrounds`,
)
.then(res => res.data),
enabled: !!appContext.currentUser,
onSuccess: data => {
data.forEach(favCamp => {
if (favCamp._id === campgroundId) setIsFavorited(true);
});
},
},
]);
Note: can also enable a query with condition using enabled prop