0

In my NextJS app, user has an opportunity to view the list and to add data there.

When user adds the item to the list, its query is invalidated with queryClient.invalidateQueries({ queryKey: ['branchList'] });.

However, when user navigates back to the list page, the query does not refetch data and user gets the obsolete list.

I've read similar issues on StackOverflow (like this one) and can confirm I use new QueryClient only once in the _app file:

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      refetchOnReconnect: false,
      retry: 1,
      staleTime: Number.POSITIVE_INFINITY,
    },
  },
});

export default function App({ Component, pageProps }: AppProps) {
  return (
    <QueryClientProvider client={queryClient}>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </QueryClientProvider>
  );
}

The query itself looks like this:

  const { data, isLoading, error } = useQuery({
    queryKey: ['branchList'],
    queryFn: getAllBranches,
  });

Also, I can see in console that the query is invalid: console screenshot

I would really appreciate any help with this issue. Thanks in advance!

N.K.
  • 301
  • 1
  • 8

1 Answers1

2

However, when user navigates back to the list page, the query does not refetch data and user gets the obsolete list.

You have set refetchOnMount to false. This is the flag that indicates that stale data or data marked as invalid should be refetched when a new component mounts that uses that data via useQuery. So basically, you have opted out of refetching.

When staleTime is set to Infinity, there is no real point in turning off all the flags. The flags are triggers at which point react query will refetch stale queries. If your queries are never stale, you can leave the flags on. That way, you'll get automatic refetches that you apparently want when you've marked them as invalid with invalidateQueries, but you wouldn't get them any time a component mounts (because of staleTime).

TkDodo
  • 20,449
  • 3
  • 50
  • 65