T
TanStack3y ago
fair-rose

Change UI state on successful data fetch from server OR cache

I have a scenario where I am fetching the options for a dropdown from server. And along with the options, the response also contains which of the options is supposed to be default selected option in the dropdown. The response of the API does not change at all, so I set the staleTime as Infinity. But whenever the component is mounted again, the default option is not being set in state in onSuccess callback. I could think of two ways to go about this. 1. Fetch the data from server and change the state in onSuccess callback. Con: I have to set staleTime to default or use refetchOnMount to always. Every time the component is mounted, the cost of unnecessary network calls is incurred. 2. Fetch the data from server and cache it by using staleTime Infinity, but then change the state in a useEffect as a consequence. Con: Unnecessary re-render caused by useEffect
2 Replies
rival-black
rival-black3y ago
Hi. If staleTime is set to Infinity there will be only one onSuccess call. It seems that the component using useQuery on next mount would have direct access to the query and thus to its default value (part of the cached data). Could you setup a minimal reproduction for further analysis?
fair-rose
fair-roseOP3y ago
Sure, I will set up a repro later today. Thanks!

Did you find this page helpful?