Search⌘ K
AI Features

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:

C++
const API_ENDPOINT = 'https://hn.algolia.com/api/v1/search?query=';
const getUrl = searchTerm => `${API_ENDPOINT}${searchTerm}`;

Into a composable API constant with its parameters:

C++
const API_BASE = 'https://hn.algolia.com/api/v1';
const API_SEARCH = '/search';
const PARAM_SEARCH = 'query=';
// careful: notice the ? in between
const getUrl = searchTerm =>
`${API_BASE}${API_SEARCH}?${PARAM_SEARCH}${searchTerm}`;

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:

Node.js
const extractSearchTerm = url => url.replace(API_ENDPOINT, '');

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 & ...