T
TanStack3y ago
fuzzy-lavender

queryClient.refetchQueries() does not fire fetch if it's requested quickly after one

Hi, I have a query to REST API and I need to refetch this query after some websocket message(message tells that information updated and I need to refetch that info from REST API again). I'm making first REST API call on page load. and there are cases, when I need to refetch information quickly after page loads(talking about less than 1sec after page loaded). I have this console.log in. my fetch function for debugging console.log("HTTP useMyAlertsQuery"); :
export const useMyAlertsQuery = (
options: Partial<UseQueryOptions<My.AlertsList.ResponseBody>>
): UseQueryResult<My.AlertsList.ResponseBody> => {
const apiClient = useApiClient();

const fetchAlerts = async (): Promise<My.AlertsList.ResponseBody> => {
// eslint-disable-next-line no-console
console.log("HTTP useMyAlertsQuery");
return await apiClient
.get<void, AxiosResponse<My.AlertsList.ResponseBody>>("/my/alerts")
.then(res => res.data);
};

return useQuery<My.AlertsList.ResponseBody>({
queryKey: myAlertKeys.all,
queryFn: fetchAlerts,
...options,
});
};
export const useMyAlertsQuery = (
options: Partial<UseQueryOptions<My.AlertsList.ResponseBody>>
): UseQueryResult<My.AlertsList.ResponseBody> => {
const apiClient = useApiClient();

const fetchAlerts = async (): Promise<My.AlertsList.ResponseBody> => {
// eslint-disable-next-line no-console
console.log("HTTP useMyAlertsQuery");
return await apiClient
.get<void, AxiosResponse<My.AlertsList.ResponseBody>>("/my/alerts")
.then(res => res.data);
};

return useQuery<My.AlertsList.ResponseBody>({
queryKey: myAlertKeys.all,
queryFn: fetchAlerts,
...options,
});
};
and I have this console.log("alerts_updated registered"); just before refetchQueries() call:
console.log("alerts_updated registered");
queryClient.refetchQueries(
{
queryKey: myAlertKeys.all,
},
{
cancelRefetch: true,
}
);
console.log("alerts_updated registered");
queryClient.refetchQueries(
{
queryKey: myAlertKeys.all,
},
{
cancelRefetch: true,
}
);
in my console log I'm getting:
:45.493 HTTP useMyAlertsQuery <-- from page load
:46.378 alerts_updated registered <-- message from mqtt(ws)
:45.493 HTTP useMyAlertsQuery <-- from page load
:46.378 alerts_updated registered <-- message from mqtt(ws)
and I'm not getting second HTTP useMyAlertsQuery log and nothing in my network tab also. I also tried invalidateQueries with multiple different options. It was the same. Is there some timelimit when cancelRefetch: true does not work? is there any other option to refetch required data? Maybe QueryKey not settled in yet? any insights would be helpful, thank you
1 Reply
fuzzy-lavender
fuzzy-lavenderOP3y ago
it seems that it works when it's wrapped in requestAnimationFrame
window.requestAnimationFrame(() => {
queryClient.refetchQueries(
window.requestAnimationFrame(() => {
queryClient.refetchQueries(

Did you find this page helpful?