T
TanStack2y ago
fair-rose

Refetching data based on another query's response

I am attempting to implement data fetching based on two queries: positionNumbers and positionId. After the initial load, if there is an update in the number of positions (maybe after success in useMutation) , I want to invalidate the positionNumbers query key and refetch only the new index for the positionId query, not all previously fetched indexes. However, currently, all indexes are refetched whenever there is an update in the number of positions. How can I achieve selective refetching of only the new index for the positionId query?
const {
data: numberOfPositions, // bigint (10n)
isSuccess: numberOfPositionsSuccess,
} = useQuery({
queryKey: [`positionNumbers`],
queryFn: () => getPositionNumbers() // Returns the number of positions
});

const numberOfPositionsNumber = Number(numberOfPositions);

const {
data,
} = useQueries({
queries: [
...(numberOfPositions && numberOfPositionsSuccess ?
Array.from({ length: numberOfPositionsNumber }).map((_n, index) => ({
queryKey: [`${index}_positionId`, account],
queryFn: () => fetchPositionIdByIndex(index), // Returns the corresponding position id by index
}))
: []),
],
combine: (results) => ({
data: results.map((result) => result.data?.toString()),
}),
});
const {
data: numberOfPositions, // bigint (10n)
isSuccess: numberOfPositionsSuccess,
} = useQuery({
queryKey: [`positionNumbers`],
queryFn: () => getPositionNumbers() // Returns the number of positions
});

const numberOfPositionsNumber = Number(numberOfPositions);

const {
data,
} = useQueries({
queries: [
...(numberOfPositions && numberOfPositionsSuccess ?
Array.from({ length: numberOfPositionsNumber }).map((_n, index) => ({
queryKey: [`${index}_positionId`, account],
queryFn: () => fetchPositionIdByIndex(index), // Returns the corresponding position id by index
}))
: []),
],
combine: (results) => ({
data: results.map((result) => result.data?.toString()),
}),
});
In summary, I need to selectively refetch only the new index for the positionId query when the number of positions changes, without refetching all previously fetched indexes. What approach should I take to achieve this?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?