The maximum amount of elements to fetch or a function returning that number. This is needed to decide when the end of the lazy loaded list was reached.
A function that specifies how to fetch elements. Takes the previous amount of performed fetches as input (starts at 0). This can be used e.g. to specify the offset in an API endpoint. This function also implicitly defines the batch size for each lazy load execution through the amount of elements returned. This amount doesn't necessarily have to be same on each execution, though it is common to do so. Changing this prop will reset the current state returned from the hook. If this function throws an error, the respective fetch attempt is treated as having returned an empty batch.
An optional object for providing additional arguments.
const DemoUseLazyLoad = () => {
const { loadMore, elements, reachedEnd, isFetching, clear } = useLazyLoad<ReactNode>(35, async (performedFetches) => {
const data = await fetch(`https://api.artic.edu/api/v1/artworks?page=${performedFetches + 1}&limit=10`);
const parsedData = await data.json();
const elements = parsedData?.data ?? [];
return elements.map((e: { title: string, id: number }) => <li key={e.id}>{e.title}</li>);
});
return (
<div>
<button onClick={loadMore} disabled={reachedEnd}>Load more</button>
<button onClick={clear}>Reset</button>
<ul>
{elements}
</ul>
{isFetching ? <b>LOADING...</b> : ""}
{reachedEnd ? <b>YOU REACHED THE END</b> : ""}
</div>
);
};
Provides a simple API for fetching data from a resource in batches.