()
| 19 | } |
| 20 | |
| 21 | function 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> |
nothing calls this directly
no test coverage detected
searching dependent graphs…