Search code examples
reactjsmongodbaxioslimit

React - Axios request page and limit not working


Why is this still loading all data and not only first 15?

const [page, setPage] = useState(1);

useEffect(() => {
    const getHistory = async () => {
      const res = await axios.get(`/api/payment?page=${page}&limit=${15}`, {
        headers: { Authorization: token },
      });
      setHistory(res.data);
    };
    getHistory();
  }, []);`

This is what happens in backend

getPayments: async (req, res) => {
    try {
      const payments = await Payments.find();
      res.json(payments);
    } catch (err) {
      return res.status(500).json({ msg: err.message });
    }
  }

Solution

  • You should actually retrieve and use your query params in the getPayments function:

    getPayments: async (req, res) => {
      try {
        const { page, limit } = req.query
        const payments = await Payments.find().skip(page * limit).limit(limit).exec();
        res.json(payments);
      } catch (err) {
        return res.status(500).json({ msg: err.message });
      }
    };