how to avoid React query calling the same api multiple times on initial render. #6542
-
Ver.4.29.19 Though both items are using the same key, but because they are almost running in the parallel once the // Inside item A and item B, there is a such a function that call useQuery based on the
function useTestQuery (id) => {
return useQuery(["test", id], apiCallFn)
}
const ItemA = () => {
const router = useRouter();
const { id } = router.query;
useTestQuery(id);
return <div />
}
const ItemB = () => {
const router = useRouter();
const { id } = router.query;
useTestQuery(id);
return <div />
} Scenario A: (not sure how to solve) // let's assume A and B are far away from the dom tree, so you know these two items are rendering almost in parallel.
// but they are inside the same page, so the "pid" is the same.
<Item_A />
<Item_B /> Scenario B: (solvable) // this also causes the api call twice, first one from A, second one from first Item_B,
// then the rest of the Item_Bs will utilize the cache
<Item_A>
{ Array({ length: 10 }).map(() => <Item B/>)}
</Item_A>
// but obviously we can wait for the pid to be ready or pass the data down to the tree
// this will only call api once
<Item_A>
{ id && Array({ length: 10 }).map(() => <Item B id={id}/>)}
</Item_A> |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
It seems like based on this one: #3630 |
Beta Was this translation helpful? Give feedback.
-
Are you sure its running with the same id value? I'm assuming that you're using NextJS where router.query is {} during prefetching. You might be running the queryFn with id as undefined initially and then running it with the actual id. This might look like its running twice. If that's the problem, you can use the enabled flag to only run the queryFn when id is defined. Something like this: useQuery(["test", id], apiCallFn, {enabled: !!id}) Also yes, the default staleTime is 0. This means, any subsequent queries after a success are going to fetched again but not while the first promise isn't resolved. (Dominik can correct me if I'm wrong here) |
Beta Was this translation helpful? Give feedback.
-
You can set |
Beta Was this translation helpful? Give feedback.
It seems like based on this one: #3630
https://stackoverflow.com/questions/72828361/what-are-staletime-and-cachetime-in-react-query
The
staleTime
will do the trick, but I'm not sure if there is any potential tradeoff or bug it might lead to if I set it to something like1000
ms.