MCPcopy Index your code
hub / github.com/ampproject/amphtml / useInfiniteQuery

Function useInfiniteQuery

src/preact/hooks/useInfiniteQuery.ts:53–119  ·  view source on GitHub ↗
({
  fetchPage,
  getNextPageParam,
}: InfiniteQueryConfig<TPage, TPageParam>)

Source from the content-addressed store, hash-verified

51 * });
52 */
53export function useInfiniteQuery<TPage, TPageParam>({
54 fetchPage,
55 getNextPageParam,
56}: InfiniteQueryConfig<TPage, TPageParam>): InfiniteQueryResponse<TPage> {
57 const [state, setState] =
58 useStateSafe<InfiniteQueryState<TPage>>(initialState);
59
60 // Use a ref to keep these current:
61 const ref = useValueRef({fetchPage, getNextPageParam, state});
62
63 // Used for ignoring outdated requests:
64 const fetchIndexRef = useRef(0);
65
66 // Loads the next page of data
67 const loadMore = useCallback(
68 async (resetting = false) => {
69 const {fetchPage, getNextPageParam, state} = ref.current;
70
71 if (!resetting && state.loading) {
72 return;
73 }
74
75 const fetchIndex = ++fetchIndexRef.current;
76
77 setState((s) => ({...s, loading: true}));
78
79 const pages: TPage[] = resetting ? [] : state.pages;
80 const lastPage = pages.length ? pages[pages.length - 1] : undefined;
81
82 try {
83 const newPage = await fetchPage({
84 pageParam: lastPage ? getNextPageParam(lastPage) : undefined,
85 });
86
87 if (fetchIndex !== fetchIndexRef.current) {
88 // A new request has been started; cancel this one:
89 return;
90 }
91
92 const nextPageParam = getNextPageParam(newPage);
93
94 setState({
95 loading: false,
96 error: null,
97 pages: [...pages, newPage],
98 hasMore: nextPageParam !== undefined && nextPageParam !== null,
99 });
100 } catch (error) {
101 if (fetchIndex !== fetchIndexRef.current) {
102 // A new request has been started; cancel this one:
103 return;
104 }
105
106 setState((s) => ({...s, loading: false, error}));
107 }
108 },
109 [ref, setState]
110 );

Callers 1

BentoListWithRefFunction · 0.90

Calls 3

useStateSafeFunction · 0.90
useValueRefFunction · 0.90
getNextPageParamFunction · 0.85

Tested by

no test coverage detected