Answers for "paging react mongoose"

0

paging react mongoose

//server

// An example of a controller function for Express.js
async getAllUser (req, res) {
    try {
      const limit = parseInt(req.query.limit); // Make sure to parse the limit to number
      const skip = parseInt(req.query.skip);// Make sure to parse the skip to number

      // We are using the '3 layer' architecture explored on the 'bulletproof node.js architecture'
      // Basically, it's just a class where we have our business logic
      const userService = new userService();
      const users = await userService.getAll(limit, skip);

      return res.status(200).json(users);
    } catch(e){
      return res.status(500).json(e)
    }
},

class UserPaginationExample {
    getAll(limit = 0, skip = 0) {
        return UsersModel.aggregate([
            { $match: {} },    // This is your query
            { $skip: skip },   // Always apply 'skip' before 'limit'
            { $limit: limit }, // This is your 'page size'
        ])  
    }
}



//client

import React, { useState, useEffect } from 'react'

const fetchUsers = (limit, skip) => {
    // Make sure you send 'limit' and 'skip' as query parameters to your node.js server
    fetch(`/api/users?limit=${limit}&skip=${skip}`) 
        .then((res) => {
            this.setState({
                users: res.data;
            })
        })
}

const userList = () => {

    const [users, setUsers] = useState([]);
    const [limit, setLimit] = useState(20);
    const [skip, setSkip] = useState(0);

    const nextPage = () => {
        setSkip(skip + limit)
    }

    const previousPage = () => {
        setSkip(skip - limit)
    }

    useEffect(() => {
        fetchUsers(limit, skip)
    }, [skip, limit])


    return (<div> 
        <div> 
            { 
                users.map(user => 
                    <div> 
                        <span> { user.name } </span>
                        <span> { user.email } </span>
                        <span> { user.lastLogin } </span>
                    </div>
                )
            }
        </div>
        <div> 
            <div onClick={nextPage}> Previous Page </div>
            <div onClick={previousPage}> Next Page </div> 
        </div>
    </div>)
}
Posted by: Guest on May-13-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language