import React from 'react'
import Link from 'next/link'
import { useInView } from 'react-intersection-observer'
import {
useInfiniteQuery,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient()
export default function App() {
return (
)
}
function Example() {
const { ref, inView } = useInView()
const {
status,
data,
error,
isFetching,
isFetchingNextPage,
isFetchingPreviousPage,
fetchNextPage,
fetchPreviousPage,
hasNextPage,
hasPreviousPage,
} = useInfiniteQuery({
queryKey: ['projects'],
queryFn: async ({
pageParam,
}): Promise<{
data: Array<{ name: string; id: number }>
previousId: number
nextId: number
}> => {
const response = await fetch(`/api/projects?cursor=${pageParam}`)
return await response.json()
},
initialPageParam: 0,
getPreviousPageParam: (firstPage) => firstPage.previousId,
getNextPageParam: (lastPage) => lastPage.nextId,
})
React.useEffect(() => {
if (inView) {
fetchNextPage()
}
}, [fetchNextPage, inView])
return (
Infinite Loading
{status === 'pending' ? (
Loading...
) : status === 'error' ? (
Error: {error.message}
) : (
<>
{data.pages.map((page) => (
{page.data.map((project) => (
{project.name}
))}
))}
{isFetching && !isFetchingNextPage
? 'Background Updating...'
: null}
>
)}
Go to another page
)
}