queryClient.refetchQueries({ stale: true }) will refetch non stale queries #9723
Send to my agentDescribe the bug#
Hello there, im using Tanstack query with Remix and i have disabled refetchOnMount to avoid unexpected double fetching behavoir and so on, the refetching on mount is handled by loaders / clientLoaders, this currently works great although when an error is thrown to the boundary and i navigate away from that boundary i manually reset the boundary, this although will avoid a refetch because refetchOnMount is false therefore i want to manually refetch stale queries see the code under
const QueryKeyContext = createContext<{
queryKeyBase?: string[];
paramNames?: string[];
searchParamNames?: string[];
}>({});
export function useQueryKey() {
return useContext(QueryKeyContext);
}
function Fallback({ error, resetErrorBoundary }: { error: unknown; resetErrorBoundary: () => void }) {
const location = useLocation();
const { queryKeyBase, paramNames, searchParamNames } = useQueryKey();
const params = useParams();
const [searchParams] = useSearchParams();
const queryKey = [
...(queryKeyBase ?? []),
...(paramNames?.map((name) => params[name]) ?? []),
...(searchParamNames?.map((name) => searchParams.get(name)) ?? []),
];
const queryClient = useQueryClient();
const errorLocation = useRef({ pathname: location.pathname, search: location.search });
useEffect(() => {
if (location.pathname !== errorLocation.current.pathname || location.search !== errorLocation.current.search) {
resetErrorBoundary();
// Because refetchOnMount is disabled by default
// we need to manually refetch the queries when the location changes
queryClient.refetchQueries({ queryKey, stale: true });
}
}, [location.pathname, location.search]);
const errorResponse = getError(error);
return (
<Wrapper className="my-8">
<title>Es gab ein Fehler</title>
<PageHeader title="Es gab ein Fehler" />
<Separator className="my-8" />
<Label className="text-lg font-medium text-red-600 mb-4">{errorResponse?.status || 500}</Label>
<Label className="text-muted-foreground">
{errorResponse?.data || "Ein unerwarteter Fehler is aufgetreten."}
</Label>
<Button onClick={() => resetErrorBoundary()} className="mt-6">
Erneut versuchen
</Button>
</Wrapper>
);
}
export function ErrorBoundaryClient({ children }: { children: React.ReactNode }) {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ReactErrorBoundary onReset={reset} FallbackComponent={Fallback}>
{children}
</ReactErrorBoundary>
)}
</QueryErrorResetBoundary>
);
}
export function withErrorBoundary<T extends React.ComponentPropsWithoutRef<any>>(
Component: React.ComponentType<T>,
queryKeyBase: string[],
paramNames?: string[],
searchParamNames?: string[],
) {
return function WrappedComponent(props: T) {
return (
<QueryKeyContext.Provider value={{ queryKeyBase, paramNames, searchParamNames }}>
<ErrorBoundaryClient>
<Component {...props} />
</ErrorBoundaryClient>
</QueryKeyContext.Provider>
);
};
}
As you can see this is the code to do that, however this will now refetch my still non stale query also i dont know why as a workaround im using this:
const QueryKeyContext = createContext<{
queryKeyBase?: string[];
paramNames?: string[];
searchParamNames?: string[];
staleTime?: number;
}>({});
export function useQueryKey() {
return useContext(QueryKeyContext);
}
function Fallback({ error, resetErrorBoundary }: { error: unknown; resetErrorBoundary: () => void }) {
const location = useLocation();
const { queryKeyBase, paramNames, searchParamNames, staleTime } = useQueryKey();
const params = useParams();
const [searchParams] = useSearchParams();
const queryKey = [
...(queryKeyBase ?? []),
...(paramNames?.map((name) => params[name]) ?? []),
...(searchParamNames?.map((name) => searchParams.get(name)) ?? []),
];
const queryClient = useQueryClient();
const errorLocation = useRef({ pathname: location.pathname, search: location.search });
useEffect(() => {
if (location.pathname !== errorLocation.current.pathname || location.search !== errorLocation.current.search) {
resetErrorBoundary();
// Because refetchOnMount is disabled by default
// we need to manually refetch the queries when the location changes
console.log(queryKey);
const isStale = Date.now() - (queryClient.getQueryState(queryKey)?.dataUpdatedAt ?? 0) > (staleTime ?? 0);
const queryState = queryClient.getQueryState(queryKey);
console.log("Query State on location change", queryState);
if (isStale) {
queryClient.refetchQueries({ queryKey });
}
}
}, [location.pathname, location.search]);
const errorResponse = getError(error);
return (
<Wrapper className="my-8">
<title>Es gab ein Fehler</title>
<PageHeader title="Es gab ein Fehler" />
<Separator className="my-8" />
<Label className="text-lg font-medium text-red-600 mb-4">{errorResponse?.status || 500}</Label>
<Label className="text-muted-foreground">
{errorResponse?.data || "Ein unerwarteter Fehler is aufgetreten."}
</Label>
<Button onClick={() => resetErrorBoundary()} className="mt-6">
Erneut versuchen
</Button>
</Wrapper>
);
}
export function ErrorBoundaryClient({ children }: { children: React.ReactNode }) {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ReactErrorBoundary onReset={reset} FallbackComponent={Fallback}>
{children}
</ReactErrorBoundary>
)}
</QueryErrorResetBoundary>
);
}
export function withErrorBoundary<T extends React.ComponentPropsWithoutRef<any>>(
Component: React.ComponentType<T>,
queryKeyBase: string[],
paramNames?: string[],
searchParamNames?: string[],
staleTime?: number
) {
return function WrappedComponent(props: T) {
return (
<QueryKeyContext.Provider value={{ queryKeyBase, paramNames, searchParamNames, staleTime }}>
<ErrorBoundaryClient>
<Component {...props} />
</ErrorBoundaryClient>
</QueryKeyContext.Provider>
);
};
}
This works like expected.
Your minimal, reproducible example#
Steps to reproduce#
Expected behavior#
await queryClient.refetchQueries({ stale: true }) // That this function only should refetch stale queries
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- OS Windows
- Browser Firefox
Tanstack Query adapter#
react-query
TanStack Query version#
5.83.0
TypeScript version#
5.8.3
Additional context#
No response
TkDodo closed this
TkDodo added labelsneeds-info
Sign in to join this conversation.
Thank you for filing this issue, but we need more information before looking into this.
Specifically, a minimal, standalone, runnable reproduction is needed - preferably with codesandbox or stackblitz.
We'll close this issue for now, but we'll certainly re-open it if there is a proper reproduction.