TanStackT
TanStack2y ago
11 replies
dead-brown

Initial data is applied when the query key is changed

This all works well until I change the query key and then it goes back to the initial data until I fetch the new data.
export const usePostInfiniteQuery = (
  postIds: number[],
  initialData?: NewPublicPosts[],
) => {
  
  return useInfiniteQuery({
    queryKey: ["fetchPosts", postIds],
    queryFn: ({ pageParam }) => fetchPosts(postIds, pageParam),

    getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => {
      if (!lastPage) {
        return null;
      }

      if (lastPage.length < 10) return null;

      return lastPageParam + 10;
    },

    initialPageParam: 0,

    retry: 0,
    enabled: false,

    placeholderData: (previousData, previousQuery) => previousData,

    // Initial data is applied when the query key is changed
    initialData: {
      pages: [initialData],
      pageParams: [0],
    },
  });
};
Was this page helpful?