Paginated Fetch
Let's extend the composable API constants so it can deal with paginated data!
We'll cover the following...
Take a closer look at the data structure and observe how the Hacker News API returns more than a list of hits. Precisely, it returns a paginated list. The page property, which is 0
in the first response, can be used to fetch more paginated sublists as results. You only need to pass the next page with the same search term to the API.
We’ll start with:
const DEFAULT_QUERY = 'redux';const PATH_BASE = 'https://hn.algolia.com/api/v1';const PATH_SEARCH = '/search';const PARAM_SEARCH = 'query=';const PARAM_PAGE = 'page=';
Now you can use the new constant to add the page parameter to your API request:
const DEFAULT_QUERY = 'redux';const PATH_BASE = 'https://hn.algolia.com/api/v1';const PATH_SEARCH = '/search';const PARAM_SEARCH = 'query=';const PARAM_PAGE = 'page=';const url = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}&${PARAM_PAGE}`;console.log(url);// output: https://hn.algolia.com/api/v1/search?query=redux&page=
The fetchSearchTopStories()
method will take the page as second argument. If you don’t provide the second argument, it will fallback to the 0
page for the initial request. Thus the componentDidMount()
and onSearchSubmit()
methods fetch the first page on the first request. ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy