Skip to content

Instantly share code, notes, and snippets.

@jdnichollsc
Created July 1, 2023 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdnichollsc/c9aa4945ee763f1d0a4828d19764a77d to your computer and use it in GitHub Desktop.
Save jdnichollsc/c9aa4945ee763f1d0a4828d19764a77d to your computer and use it in GitHub Desktop.
Custom hook for infinite scrolling using React Query
import { useInfiniteQuery } from '@tanstack/react-query';
import { MarketplaceItem } from '../models';
import { getMarketplaceItems } from '../services';
export type UseMarketplaceItemsProps = {
query: string;
initialData?: MarketplaceItem[];
from?: number;
size?: number;
};
export const useMarketplaceItems = ({
query,
initialData,
size,
}: UseMarketplaceItemsProps) => {
return useInfiniteQuery<MarketplaceItem[]>(
['marketplace-items', query],
({ pageParam = 1 }) => {
const from = (pageParam - 1) * size;
return getMarketplaceItems(query, from, size)
},
{
staleTime: 100000,
keepPreviousData: true,
refetchOnWindowFocus: false,
getNextPageParam: (lastPage: unknown[], pages: unknown[]) => {
let nextPage: number;
if (lastPage?.length === size && pages) {
nextPage = (pages.length || 0) + 1;
}
return nextPage;
},
...(initialData && {
initialData: {
pages: [initialData],
pageParams: [null],
},
}),
useErrorBoundary: false,
},
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment