Solution Review: Paginated Fetch
Explore techniques for handling paginated data fetches in React using the Hacker News API. Learn to extend API endpoints, manage state to append new data without replacing existing lists, and improve user experience by optimizing conditional rendering during asynchronous fetches.
We'll cover the following...
Solution
First, extend the API constant so it can deal with paginated data later. We will turn this one constant:
Into a composable API constant with its parameters:
Fortunately, we don’t need to adjust the API endpoint, because we extracted a common getUrl function for it. However, there is one spot where we must address this logic for the future:
In the next steps, it won’t be sufficient to replace the base of our API endpoint, which is no longer in our code. With more parameters for the API endpoint, the URL becomes more complex. It will change from X to Y:
// X
https://hn.algolia.com/api/v1/search?query=react
// Y
https://hn.algolia.com/api/v1/search?query=react&page=0
It’s better to extract the search term by extracting everything between ? and & ...