T
TanStack4y ago
mere-teal

Changing queryKey not refetching

My render has this code:
const [id, setId] = useState(props.initialId);
useQuery(['m', id], queryFn, { refetchOnMount: 'always', cacheTime: Infinity, staleTime: Infinity, onSuccess: successCallback, notifyOnChangeProps: ['status', 'error', 'isFetching', 'data'] });
const [id, setId] = useState(props.initialId);
useQuery(['m', id], queryFn, { refetchOnMount: 'always', cacheTime: Infinity, staleTime: Infinity, onSuccess: successCallback, notifyOnChangeProps: ['status', 'error', 'isFetching', 'data'] });
In the success callback I do setId('some other id') - this is not making react-query refetch. I'm using v3. Anyone have any ideas?
9 Replies
mere-teal
mere-tealOP4y ago
oh wow, interesting. setting staleTime to 0 fixes it. im not sure why that is, does anyone else know?
like-gold
like-gold4y ago
That's because a query will only refetch if it's considered stale. Since you're forcing stale time to Infinity, it won't trigger a refetch, unless you manually invalidate it using invalidateQueries
mere-teal
mere-tealOP4y ago
thanks @jpedroh thats interesting. i thought the refetchOnMount: 'always' would make it refetch no matter what.
eager-peach
eager-peach4y ago
yes, it does, if there is a component mounting happening. a change in querykey is not a "mount" event
mere-teal
mere-tealOP4y ago
ah is there a way to make it refetch on query key change?
eager-peach
eager-peach4y ago
That happens automatically depending on staleTime
mere-teal
mere-tealOP4y ago
Ah, so my staleTime is Infinity right now, if I set it to like 99999999999 should that that trigger it instantly on query key change? (i can test if it would of course, but just trying to understand the logic so i can think in the react-query way)
eager-peach
eager-peach4y ago
no
mere-teal
mere-tealOP4y ago
ah got it so just if it goes stale or gets remounted, to solve the remount im putting the query into its own component. so it remounts when key changes which is query id.

Did you find this page helpful?