In my application I have spots saved in firestore and I fetch them in React Native using Tanstack's useQuery. At start I first fetch all spots at a specific location and display them on a map. The user can then press on a spot and a detail page will open, neatly displaying the data. How should I set the queryKey of the mapSpots, such that in the detail page when using useSpot(id) it will use the cached spot from useMapSpots and also to be able to later invalidate specific spots instead all of the mapSpots? Do I need to modify fetchAllSpotFromLocation? I cannot use ['spot',id] in useMapSpots since before the queryFn has been executed I do not know the ids.
export function useMapSpots(latitude, longitude, range) {
return useQuery({
queryKey: ['mapSpots'],
queryFn: () => fetchAllSpotFromLocation(latitude, longitude, range),
enabled: true,
});
}
export function useSpot(id) {
return useQuery({
queryKey: ['spot', id],
queryFn: () => fetchSpot(id),
enabled: !!id,
});
}
const fetchAllSpotFromLocation = async (userLatitude, userLongitude, range) => {
const center = [userLatitude, userLongitude];
const bounds = geofire.geohashQueryBounds(center, range * 1000);
let downloadedSpots = [];
// Iterate through each bound
for (const b of bounds) {
let queries = [];
// Always query for public spots
const publicQuery = query(
collection(firestore, 'spots'),
orderBy('geoHash'),
where('public', '==', true),
startAt(b[0]),
endAt(b[1])
);
queries.push(getDocs(publicQuery));
// Execute the queries and combine results
const spotDataArrays = await Promise.all(queries);
const spots = spotDataArrays.flatMap(spotData =>
spotData.docs.map(doc => ({ id: doc.id, ...doc.data() }))
);
downloadedSpots.push(...spots);
}
return downloadedSpots;
};