Pagination
Discover how we can enable pagination when fetching results from an API.
What is pagination?
Pagination is used when we have many values to organize into pages. The user can switch between these pages, and we can also set how many values we want to see on each page. A typical example is an e-commerce store where we may display 20 products per page, and the user can navigate between them.
Pagination can be handled differently depending on where our data is coming from. For our use, when using the Pixabay API, this is handled in the query string. We can pass in how many images per page we want and also the page number to fetch:
const { data: images } = await useFetch(() => `?key=${apiKey}&q=${searchTerm.value}&page=1&per_page=10`,{baseURL: baseUrl,});
Pagination with the Pixabay API
The above example shows how we can add both the page
and the per_page
parameters to the query string. Since we request the first page and 10 images, we will receive images 1–10. Switching this to page two will request images 11–20.
By default, useFetch
will try to cache the results to avoid making unnecessary extra requests. This means a faster user experience when a previous page ...