MCPcopy
hub / github.com/TanStack/query / Example

Function Example

examples/react/load-more-infinite-scroll/src/pages/index.tsx:21–121  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

19}
20
21function Example() {
22 const { ref, inView } = useInView()
23
24 const {
25 status,
26 data,
27 error,
28 isFetching,
29 isFetchingNextPage,
30 isFetchingPreviousPage,
31 fetchNextPage,
32 fetchPreviousPage,
33 hasNextPage,
34 hasPreviousPage,
35 } = useInfiniteQuery({
36 queryKey: ['projects'],
37 queryFn: async ({
38 pageParam,
39 }): Promise<{
40 data: Array<{ name: string; id: number }>
41 previousId: number
42 nextId: number
43 }> => {
44 const response = await fetch(`/api/projects?cursor=${pageParam}`)
45 return await response.json()
46 },
47 initialPageParam: 0,
48 getPreviousPageParam: (firstPage) => firstPage.previousId,
49 getNextPageParam: (lastPage) => lastPage.nextId,
50 })
51
52 React.useEffect(() => {
53 if (inView && hasNextPage && !isFetchingNextPage) {
54 fetchNextPage()
55 }
56 }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
57
58 return (
59 <div>
60 <h1>Infinite Loading</h1>
61 {status === 'pending' ? (
62 <p>Loading...</p>
63 ) : status === 'error' ? (
64 <span>Error: {error.message}</span>
65 ) : (
66 <>
67 <div>
68 <button
69 onClick={() => fetchPreviousPage()}
70 disabled={!hasPreviousPage || isFetchingPreviousPage}
71 >
72 {isFetchingPreviousPage
73 ? 'Loading more...'
74 : hasPreviousPage
75 ? 'Load Older'
76 : 'Nothing more to load'}
77 </button>
78 </div>

Callers

nothing calls this directly

Calls 1

useInfiniteQueryFunction · 0.90

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…