TanStackT
TanStack11mo ago
1 reply
excited-coffee

Infinite query fetches next page on every rerender. Why?

I toggle a setting showOwnOnly which triggers a rerender. On that rerender, I can see, that the infiniste query i am using fetches the next page.
The queryKey is stable (otherwise it probably would start at page 0 again).

Here is how I use the query:

const today = new Date();
const date = new Date(today.getFullYear(), today.getMonth(), today.getDate());

const { events: ownEvents } = useOwnEvents(); // not a query but a store
const showOwnOnly = useSettingsStore((state) => state.showOwnOnly); // this is what i toggle

const { data, fetchNextPage, isFetchingNextPage, isFetched } = useEvents({
    startDateTime: stripMillis(date), // this is stable for a full day
    size: 20,
});

const flatEventList = data?.pages.flatMap((page) => page.events ?? []) ?? [];
const events = showOwnOnly ? ownEvents : [...flatEventList, ...ownEvents ];

return <... using events to render a list >


useEvents is this:
export function useEvents(
  filters: Record<string, any> = {}
) {
  return useInfiniteQuery({
    queryKey: ["events", filters],
    queryFn: async () => {
      return fetchSomething();
    },
    initialPageParam: 0,
    getNextPageParam: (lastPage) => {
      if (lastPage.page.number < lastPage.page.totalPages - 1) {
        return lastPage.page.number + 1;
      } else {
        return undefined;
      }
    },
    staleTime: Infinity,
    refetchOnMount: false,
    refetchOnWindowFocus: false,
    refetchOnReconnect: false
  });
}


Is this by design? How can I stop that from happening?
Was this page helpful?