I am fetching objects from an API simply with
getData() {
fetch('API_URL').then(res => res.json()).then(data => {
this.setState({ jobs: data.jobs });
}).catch(console.log);
}
componentDidMount() {
this.getData();
}
But I want to be able to click a button to load more objects.
I guess that I should create the API such that it only prints e.g. 10 objects at a time and keeps a variable "pageNumber" and if I click the "load more" button, it should fetch from next page and append the new objects.
Is this the right approach? Or can I simply load thousands of objects when mounting the component and use React to limit how many are seen? I guess this would be a very inefficient way to fetch the data, but I am not really sure how well React handles this.
Can I, for instance, in my API just keep print X number of objects and in my fetch request decide how many objects are loaded? So when I have pressed "load more" 2 times, the API endpoint will return 30 objects instead of only 10 - even though the first 20 have already been fetched before?
I have tried searching for pagination in React, but I only get a lot of pagination libraries. I just want to understand the very basic initial fetching and the fetching following clicking load more.
Edit
But if I have an API endpoint which returns something like
{
page: 1,
objectsPerPage: 10,
numPages: 30,
objects: [
...
]
}
and I am initially retrieving the objects on page 1, and every time I click "Load more", I increase the page number and append the objects on the next page (with this.setState({ jobs: this.state.jobs.concat(data.jobs) }); where data.jobs is the list of objects on the next page, then I would be afraid that new objects are created in the database, so which objects belong to which page is completely screwed up and not all or some duplicates are shown.