'Getting an issue to implement load more feature using node mongo express react
I am trying to implement load more feature in my react application. And for that I am creating an endpoint to implement load more. So, whenever app load it is fetching initial 5 data but unable to fetch next 5 data after clicking on load more button from UI.
Here is controller for that
export const loadMoreBlogs = async (req, res) => {
const { skip } = req.body;
try {
const limit = 5;
const blogs = await BlogModel.find().skip(skip).limit(limit);
res.status(200).json(blogs);
} catch (error) {
res.status(404).json({ message: error.message });
}
};
React component
import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { loadMoreBlogs, setLoadedBlogs } from "../redux/features/blogSlice";
const Blogs = () => {
const [skip, setSkip] = useState(0);
const dispatch = useDispatch();
const limit = 5;
const { loadBlogs } = useSelector((state) => ({ ...state.blog }));
useEffect(() => {
dispatch(loadMoreBlogs(skip));
}, [skip]);
console.log("skip", skip);
const handleLoadMore = () => {
const skipTo = skip + limit;
dispatch(loadMoreBlogs(skipTo));
setSkip(skipTo);
setLoadedBlogs(loadBlogs);
};
return (
<>
{loadBlogs?.map((item) => (
<h2>{item.title}</h2>
))}
<button onClick={handleLoadMore}>Load More</button>
</>
);
};
export default Blogs;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
