TanStack / query

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
https://tanstack.com/query
MIT License
41.79k stars 2.84k forks source link

QueryCache in QueryClient is not reflecting state changes inside onError callback #7685

Open alikashan opened 2 months ago

alikashan commented 2 months ago

Describe the bug

Offline mode feature in React native Typescript Application.

There is switch view in my Settings screen where user can switch to offline mode and this switch is bind with React Context. the only requirement is to disable all error toasts when offline mode is enabled but the problem is queryCache.onError callback always reflects the initial value of context ie isOffline value is always false inside onError callback regardless of user action on switch.

Your minimal, reproducible example


Steps to reproduce

call refetch function on any screen focus.

This is my minimal reproducible code with simple QueryClient object


export var queryClient: QClient;

export default function QueryClientInstanceProvider(props: PropsWithChildren) {
  const t = useTranlator();
  const toast = useToast();
  const { isOffline } = useOfflineMode();

  const onError = React.useCallback(
    (error: any) => {
      console.log('🍪 QUERYCLIENTCONTEXT.TSX ==> in mehtods', isOffline, error.code);
      if (isOffline && error.code === ErrorCodes.NetworkError) return;

      toast.show({ description: t(error.message) });
    },
    [isOffline]
  );

  queryClient = React.useMemo(() => {
    return new QClient({
      queryCache: new QueryCache({
        onError,
      }),
      defaultOptions: {
        mutations: {
          onError,
        },
        queries: {
          retry: false,
          refetchOnWindowFocus: false,
          gcTime: 1000 * 60 * 5,
        },
      },
    });
  }, [isOffline]);

  return (
    <QueryClientProvider client={queryClient}>
      <Box width={'full'} height={'full'}>
        {props.children}
      </Box>
    </QueryClientProvider>
  );
}

Expected behavior

onError should reflect the correct state value

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Android IOS

Tanstack Query adapter

react-query

TanStack Query version

v5.29.2

TypeScript version

v5.4.5

Additional context

No response

TkDodo commented 2 months ago

if isOffline changes, you are throwing away the cache and create a new one. Even if this works, it isn't good. Creating a queryClient in useMemo is also "wrong" because again, re-creating the cache from scratch isn't what you want.

I would not close over isOffline and create a new function / cache every time it changes, but rather provide an imperative way to read that value.

Not sure how useOfflineMode is implemented, but if it's e.g. a zustand store, you could just do store.getState().isOffline as an imperative action inside the onError callback.