Skip to content

Instantly share code, notes, and snippets.

@thrashr888
Last active March 24, 2018 03:32
Show Gist options
  • Select an option

  • Save thrashr888/197dd954d10e66e0aa618924affc6b47 to your computer and use it in GitHub Desktop.

Select an option

Save thrashr888/197dd954d10e66e0aa618924affc6b47 to your computer and use it in GitHub Desktop.
recursive fetch for wordpress API
let lastPage = 25;
let self = this;
function getPage(thisPage) {
console.log('Loading page', thisPage);
fetch(self.state.url + '&page=' + thisPage)
.then(response => {
if (response.headers.has('X-WP-TotalPages')) {
lastPage = response.headers.get('X-WP-TotalPages');
}
return response.json();
})
.catch(error => {
console.error('Error fetching API page', thisPage, error);
})
.then(data => {
if (!data) return;
console.log('Loaded page', thisPage, data);
let listings = self.state.listings.concat(data.map(self.mapListing));
self.setState({
listings,
});
if (thisPage < lastPage) {
getPage(++thisPage);
}
})
.catch(error => {
console.error('Error fetching API page', thisPage, error);
});
}
getPage(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment