The type of the data items.
The state setter function to update the data array.
The state setter function to update whether there are more pages to load.
Optional
hasMore: boolean = trueBoolean indicating whether there are more pages to fetch.
Optional
initialPage: number = 1The initial page number to start from.
Optional
limit: number = 10The number of items per page.
The returning object contains:
appendNextPage
: Function to load the next page of data and append it to the current data.checkHasMore
: Function that checks if there are more pages based on the fetched data.currentPage
: The current page number.hasMore
: Boolean indicating whether there are more pages to fetch.refreshLastPage
: Function to refresh the last page of data with updated results.Implementation Details:
useState
manages the current page, data (setData
), and pagination
state (hasMore
), updating them as new data is fetched.appendNextPage
fetches and appends new data to the existing
state, applying an optional mutation
function to transform the data.refreshLastPage
re-fetches and updates the last page, removing any
extra items from previous pages that don't fit the limit
.checkHasMore
sets hasMore
to false
if the fetched data is fewer
than the limit
, indicating no more pages.fetch
function, logging or re-throwing with context.mutation
function allows for data transformation before appending it to the state.Optional
mutation: ((data) => T)Optional
mutation: ((data) => T)import { usePagination } from 'react-playmakers';
const fetchItems = async ({ page, limit }) => {
const response = await fetch(`https://api.example.com/items?page=${page}&limit=${limit}`);
return await response.json();
};
const MyComponent = () => {
const [items, setItems] = useState([]);
const [hasMore, setHasMore] = useState(true);
const { appendNextPage, refreshLastPage, currentPage, hasMore: moreItems } = usePagination(
setItems,
setHasMore,
hasMore,
1,
10
);
useEffect(() => {
// Initial fetch for the first page
appendNextPage(fetchItems);
}, []);
const loadMore = () => {
if (moreItems) {
appendNextPage(fetchItems);
}
};
const refresh = () => {
refreshLastPage(fetchItems);
};
return (
<div>
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
{moreItems && <button onClick={loadMore}>Load More</button>}
<button onClick={refresh}>Refresh Last Page</button>
</div>
);
};
Generated using TypeDoc
A custom hook for managing pagination in a React component.