Skip to content

Commit 12fd20e

Browse files
committed
chore: fix pagination
1 parent 6c9bf74 commit 12fd20e

3 files changed

Lines changed: 40 additions & 22 deletions

File tree

backend/controllers/blogController.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,11 @@ function generateBlogId(title: string): string {
3434
export const getBlogs = async (req: NextRequest) => {
3535
const getSkip = req.nextUrl.searchParams.get("skip");
3636
let parsedSkip = 0;
37-
if (getSkip) parsedSkip = parseInt(getSkip)
37+
if (getSkip) {
38+
parsedSkip = parseInt(getSkip);
39+
}
40+
41+
console.log("parsedSkip ==>", parsedSkip);
3842

3943
try {
4044
const limit = parsedSkip === 0 ? 8 : 4;

components/blog/main/blogfeed/blogFeed.tsx

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,26 @@ const BlogFeed = () => {
3131
onLoadMore: () => loadMoreBlogs(),
3232
});
3333

34-
const loadMoreBlogs = () => {
35-
setLoading((prev) => ({ ...prev, more: true }));
36-
setPagination((prev) => ({ ...prev, fetchedCount: prev.fetchedCount + 4 }));
34+
const loadMoreBlogs = async () => {
35+
if (loading.more || !pagination.hasMore) return; // Prevent multiple calls
36+
37+
setLoading((prev) => ({ ...prev, more: true })); // set loading to be true
38+
39+
try {
40+
const res = await getBlogs(pagination.fetchedCount); //fetch new blogs
41+
setBlogs((prevBlogs) => [...prevBlogs, ...res.blogs]); // add new blogs with previous blogs
42+
setPagination((prev) => ({
43+
fetchedCount: prev.fetchedCount + res.blogs.length, // increase fetched blogs count
44+
hasMore: res.hasMore, //update hasMore state
45+
}));
46+
} catch (error) {
47+
console.error("Error loading more blogs", error);
48+
} finally {
49+
setLoading((prev) => ({ ...prev, more: false })); //set loading to be false
50+
}
3751
};
3852

53+
//function to fetch blogs based on category
3954
const fetchBlogs = useCallback(async () => {
4055
if (!userInfo) return;
4156

@@ -48,8 +63,12 @@ const BlogFeed = () => {
4863
switch (activeCategory) {
4964
case "Personalized":
5065
const res = await getBlogs(pagination.fetchedCount);
51-
fetchedBlogs = res.blogs;
52-
hasMoreBlogs = res.hasMore;
66+
fetchedBlogs = res.blogs; // set blogs to *fetchedBlogs* array
67+
setPagination((prev) => ({
68+
...prev,
69+
fetchedCount: prev.fetchedCount + res.blogs.length // increase fetched blogs count
70+
}));
71+
hasMoreBlogs = res.hasMore; //update hasMore state
5372
break;
5473
case "Following":
5574
fetchedBlogs = await getFollowingBlogs(userInfo._id);
@@ -71,7 +90,9 @@ const BlogFeed = () => {
7190
}, [activeCategory, pagination.fetchedCount, userInfo?._id]);
7291

7392
useEffect(() => {
74-
fetchBlogs();
93+
if (pagination.fetchedCount === 0) {
94+
fetchBlogs();
95+
}
7596
}, [fetchBlogs]);
7697

7798
const handleCategoryChange = (category: string) => {
@@ -101,7 +122,11 @@ const BlogFeed = () => {
101122

102123
<div className="flex flex-col pt-2">
103124
{blogs.map((blog, index) => (
104-
<div key={blog._id} ref={index === blogs.length - 1 ? infiniteRef : null}>
125+
<div
126+
key={blog._id}
127+
// assign *infiniteRef* to the last blog so that when the blog is in view, it would trigger a fetch for more blogs
128+
ref={index === blogs.length - 1 ? infiniteRef : null}
129+
>
105130
<BlogItem
106131
blog={blog}
107132
handleDeletePopup={() => setDeleteBlogPopup(true)}

components/blog/main/blogfeed/blogItem.tsx

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Dispatch, SetStateAction, useState, useRef } from "react";
1+
import { Dispatch, SetStateAction, useState } from "react";
22
import Image from "next/image";
33
import Link from "next/link";
44
import { Heart, MessageCircle, Bookmark, Ellipsis } from "lucide-react";
@@ -31,7 +31,6 @@ const BlogItem = ({ blog, handleDeletePopup, openBlogId, setOpenBlogId, isLastBl
3131
const { isBookmarked, isBookmarkLoading, handleBookmarkToggle } = useBookmarks();
3232
const { following, isLoading, handleFollow, handleUnfollow } = useFollowStatus(blog.authorId._id);
3333
const [provider, setProvider] = useState<TiptapCollabProvider | null>(null);
34-
const tagColors = ['#6941C6', '#026AA2', '#C11574'];
3534

3635
const { previewText, timePublished } = handleBlogContentPreview({
3736
blogContent: blog.content,
@@ -67,6 +66,7 @@ const BlogItem = ({ blog, handleDeletePopup, openBlogId, setOpenBlogId, isLastBl
6766
<p className="text-xs text-black hover:underline">{blog.authorId.name}</p>
6867
</Link>
6968
</div>
69+
7070
{/* Blog content preview */}
7171
<Link href={`/${blog.authorId.username}/${blog.blogId}`}>
7272
<div className="flex items-start justify-between">
@@ -85,6 +85,7 @@ const BlogItem = ({ blog, handleDeletePopup, openBlogId, setOpenBlogId, isLastBl
8585
)}
8686
</div>
8787
</Link>
88+
8889
{/* Blog metadata and actions */}
8990
<div className="flex items-center text-sm justify-between max-w-[65%]">
9091
<Link href={`/${blog.authorId.username}/${blog.blogId}`} className="w-full">
@@ -105,18 +106,6 @@ const BlogItem = ({ blog, handleDeletePopup, openBlogId, setOpenBlogId, isLastBl
105106
</div>
106107
</Link>
107108
<div className="flex items-center space-x-6">
108-
<div className="hidden sm:flex items-center space-x-2">
109-
{/* TODO: add more tags support*/}
110-
{blog.tags.slice(0, 1).map((tag, index) => (
111-
<p
112-
key={tag}
113-
className="text-[11px] opacity-90 border rounded-3xl px-2 py-[1px]"
114-
style={{ color: tagColors[index % tagColors.length], borderColor: tagColors[index % tagColors.length] }}
115-
>
116-
{tag}
117-
</p>
118-
))}
119-
</div>
120109
<button onClick={() => handleBookmarkToggle(blog._id)} disabled={isBookmarkLoading}>
121110
<Bookmark size={18} strokeWidth={1} fill={isBookmarked[blog._id] ? "black" : "none"} />
122111
</button>

0 commit comments

Comments
 (0)