showing results for - "paging react mongoose"
Adame
14 Jan 2017
1//server
2
3// An example of a controller function for Express.js
4async getAllUser (req, res) {
5    try {
6      const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
7      const skip = parseInt(req.query.skip);// Make sure to parse the skip to number
8
9      // We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
10      // Basically, it's just a class where we have our business logic
11      const userService = new userService();
12      const users = await userService.getAll(limit, skip);
13
14      return res.status(200).json(users);
15    } catch(e){
16      return res.status(500).json(e)
17    }
18},
19
20class UserPaginationExample {
21    getAll(limit = 0, skip = 0) {
22        return UsersModel.aggregate([
23            { $match: {} },    // This is your query
24            { $skip: skip },   // Always apply 'skip' before 'limit'
25            { $limit: limit }, // This is your 'page size'
26        ])  
27    }
28}
29
30
31
32//client
33
34import React, { useState, useEffect } from 'react'
35
36const fetchUsers = (limit, skip) => {
37    // Make sure you send 'limit' and 'skip' as query parameters to your node.js server
38    fetch(`/api/users?limit=${limit}&skip=${skip}`) 
39        .then((res) => {
40            this.setState({
41                users: res.data;
42            })
43        })
44}
45
46const userList = () => {
47
48    const [users, setUsers] = useState([]);
49    const [limit, setLimit] = useState(20);
50    const [skip, setSkip] = useState(0);
51
52    const nextPage = () => {
53        setSkip(skip + limit)
54    }
55
56    const previousPage = () => {
57        setSkip(skip - limit)
58    }
59
60    useEffect(() => {
61        fetchUsers(limit, skip)
62    }, [skip, limit])
63
64
65    return (<div> 
66        <div> 
67            { 
68                users.map(user => 
69                    <div> 
70                        <span> { user.name } </span>
71                        <span> { user.email } </span>
72                        <span> { user.lastLogin } </span>
73                    </div>
74                )
75            }
76        </div>
77        <div> 
78            <div onClick={nextPage}> Previous Page </div>
79            <div onClick={previousPage}> Next Page </div> 
80        </div>
81    </div>)
82}
queries leading to this page
paging react mongoosepaging react mongoose