I'm building a web app using Next.JS and Node. I also created my own API with node which is requested by Next.JS.
One endpoint that i call send data to my front as an array, and then i'm displaying the content of each object of the array.
But sometimes, my array contains hundreds of objects and i can't display them all at one time because it would make to much processing and data for the browser.
So i want to make my API (Node) to send me objects of the array by batch.
I'd like to pass a body to a Post request like:
{
...,
"length": 10
}
and the node sends me the first 10 objects, then the second 10 objects ...
Does someone know how to implement that ? Are there some libraries or anything else helping to build that ?
Have a nice day, Thank you
CodePudding user response:
Yes you can achieve sending data in batches using pagination concept on backend. Only thing you need to pass from frontend is page-no Following is a simple example of pagination you can achieve
app.get('/api/posts', (req, res) => {
const pageCount = Math.ceil(posts.length / 10);
let page = parseInt(req.query.p);
if (!page) { page = 1;}
if (page > pageCount) {
page = pageCount
}
res.json({
"page": page,
"pageCount": pageCount,
"posts": posts.slice(page * 10 - 10, page * 10)
});
});
Hope ,this shall give you an idea to implement pagination