React hooks to interact with an API from a stateless component using axios.
npm i react-api-hooks -sAn example showing how the useParams and useAPI hooks can be used together to paginate results from an API.
The useParams hook keeps a params object in it's state, that can be used when making calls to the API.
The API uses offset pagination, by updating the startIndex param, the component can paginate through the results.
const PaginationExample = () => {
const { params, updateParams } = useParams(booksInitialParams);
const { data = [], error, isLoading } = useAPI(booksURL, { params });
const pagination = new OffsetPagination(data.items || [], params, updateParams, 5);
if (error) {
return <Error error={error} />;
}
return (
<>
{isLoading ? <Loading /> : <GoogleBooksList data={data} />}
<Paginator
hasNext={pagination.hasNextPage()}
hasPrevious={pagination.hasPreviousPage()}
pageCnt={pagination.getPageCnt()}
onNext={pagination.onNext}
onPrevious={pagination.onPrevious}
/>
</>
);
};
export default PaginationExample;
class OffsetPagination {
constructor(data, params, updateParams, pageSize) {
this.data = data;
this.params = params;
this.updateParams = updateParams;
this.pageSize = pageSize;
}
onNext = () => this.updateParams({ startIndex: this.getCurrentOffset() + this.pageSize });
onPrevious = () => this.updateParams({ startIndex: this.getCurrentOffset() - this.pageSize });
hasPreviousPage = () => this.params.startIndex || 0 > 0;
hasNextPage = () => this.data.length === this.pageSize;
getCurrentOffset = () => this.params.startIndex || 0;
getPageCnt = () => Math.round(this.getCurrentOffset() / this.pageSize) + 1;
}
export default OffsetPagination;