Created
July 1, 2023 00:50
-
-
Save jdnichollsc/c9aa4945ee763f1d0a4828d19764a77d to your computer and use it in GitHub Desktop.
Custom hook for infinite scrolling using React Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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