...

/

Solution Review: Paginated Fetch

Solution Review: Paginated Fetch

Learn about paginated fetch in a react app.

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:

Press + to interact
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:

Press + to interact
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:

Press + to interact
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 ? ...