-
Notifications
You must be signed in to change notification settings - Fork 1
/
PostListInfinite.tsx
75 lines (63 loc) · 1.88 KB
/
PostListInfinite.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// components/PostListInfinite.tsx
"use client";
import React, { useState, useRef, useEffect } from "react";
import PostCard from "./PostCard";
import { Post } from "@/types/Post";
import { getPosts } from "@/actions/getPosts";
import { POSTS_PER_PAGE } from "@/config/constants";
type PostListProps = {
initialPosts: Post[];
};
export default function PostListInfinite({ initialPosts }: PostListProps) {
const [offset, setOffset] = useState(POSTS_PER_PAGE);
const [posts, setPosts] = useState<Post[]>(initialPosts);
const [hasMoreData, setHasMoreData] = useState(true);
const scrollTrigger = useRef(null);
const loadMorePosts = async () => {
if (hasMoreData) {
const apiPosts = await getPosts(offset, POSTS_PER_PAGE);
if (!apiPosts.length) {
setHasMoreData(false);
}
setPosts((prevPosts) => [...prevPosts, ...apiPosts]);
setOffset((prevOffset) => prevOffset + POSTS_PER_PAGE);
}
};
useEffect(() => {
if (typeof window === "undefined" || !window.IntersectionObserver) {
return;
}
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
loadMorePosts();
}
},
{ threshold: 0.5 }
);
if (scrollTrigger.current) {
observer.observe(scrollTrigger.current);
}
return () => {
if (scrollTrigger.current) {
observer.unobserve(scrollTrigger.current);
}
};
}, [hasMoreData]);
return (
<>
<div className="post-list [counter-reset: post-index]">
{posts?.map((post) => (
<PostCard key={post.id} post={post} />
))}
</div>
<div className="text-center text-slate-600 mt-5">
{hasMoreData ? (
<div ref={scrollTrigger}>Loading...</div>
) : (
<p className="text-slate-600">No more posts to load</p>
)}
</div>
</>
);
}