Skip to content

Instantly share code, notes, and snippets.

@nurmdrafi
Last active May 11, 2022 12:44
Show Gist options
  • Save nurmdrafi/8201c848222ab3afe972b7f7411eac50 to your computer and use it in GitHub Desktop.
Save nurmdrafi/8201c848222ab3afe972b7f7411eac50 to your computer and use it in GitHub Desktop.

Steps to follow for pagination

Step - 1

Getting total number of products from Database (Server side)

app.get('productCount', async (req, res) =>{
  const count = await productColllection.estimatedDocumentCount();
res.send({count});
});

Step - 2

Get page count (Client Side)

const count = data.count;
const pages = Math.ceil(count/10); // use Math.ceil() for prevent fraction

Step - 3

Create pagination buttton (Clieny side)

Array() // [] empty array
Array(8) // [empty x 8] empty array with length 8
[...Array(8)] // [undefined,...] getting each of 8 empty elements
[...Array(8).keys()] // [0, 1, 2, 3, 4, 5, 6, 7] getting index numbers of 8 elements
[...Array(8).keys].map()(number => <button>{number}</ button> // make buttons inside map for 8 indices

Step - 4

Set page & size state (Client side)

[...Array(8).keys()]
.map(number => <button className={page === number ? 'selected' : ''}
onClick={() => setPage(number)}>
{number}
<button>)
const count = data.count;
const pages = Math.ceil(count/10);
setPageCount(pages);

Step - 5

Fetching products according to query(page, size)

fetch(`http://localhost:5000/product?page=${page}&size=${size}`)

Step - 6

Getting page & size from req.query (Server side)

const page = parseInt(req.query.page);
const size = parseInt(req.query.size);

Step - 7

Get products (Server side)

if(page || size){
  products = await cursor.skip(page*size).limit(size).toArray();
} else{
  products = await cursor.toArray();
}

Page 0 => skip: 0 get: 0-10(10)

Page 1 => skip: 1*10 get: 11-20(10)

Page 2 => skip: 2*10 get: 21-30(10)

Page 3 => skip: 3*10 get: 31-40(10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment