|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useCallback, useEffect, useRef, useState } from 'react'; |
| 4 | + |
| 5 | +import { getInfiniteScrollData } from '@/features/post/post-list/api/post-infinite-scroll'; |
| 6 | +import { PostItem } from '@/features/post/post-list/ui/post-item'; |
| 7 | +import { formatToLocaleDate } from '@/shared/lib/format-date'; |
| 8 | +import { Post } from '@/shared/types/post-types'; |
| 9 | + |
| 10 | +type InfiniteScrollProps = { |
| 11 | + postList: Post[]; |
| 12 | + lastPostId: string | null; |
| 13 | + hasMore: boolean; |
| 14 | +}; |
| 15 | + |
| 16 | +export function InfiniteScroll({ |
| 17 | + postList, |
| 18 | + lastPostId, |
| 19 | + hasMore, |
| 20 | +}: InfiniteScrollProps) { |
| 21 | + const [loading, setLoading] = useState(false); |
| 22 | + const [posts, setPosts] = useState<Post[]>(postList); |
| 23 | + const [cursor, setCursor] = useState(lastPostId ? lastPostId : null); |
| 24 | + |
| 25 | + const loadMorePosts = useCallback(async () => { |
| 26 | + if (!hasMore || loading || !cursor) return; |
| 27 | + |
| 28 | + setLoading(true); |
| 29 | + |
| 30 | + try { |
| 31 | + const { data } = await getInfiniteScrollData(cursor, 10); |
| 32 | + setPosts((prevPosts) => [...prevPosts, ...data]); |
| 33 | + const lastItem = data.at(-1); |
| 34 | + setCursor(lastItem ? lastItem.id : null); |
| 35 | + } catch (error) { |
| 36 | + console.error('Failed to fetch more posts:', error); |
| 37 | + } finally { |
| 38 | + setLoading(false); |
| 39 | + } |
| 40 | + }, [cursor, hasMore, loading]); |
| 41 | + |
| 42 | + const target = useRef<HTMLHeadingElement>(null); |
| 43 | + |
| 44 | + useEffect(() => { |
| 45 | + const observer = new IntersectionObserver((entries) => { |
| 46 | + const firstEntry = entries[0]; |
| 47 | + if (firstEntry?.isIntersecting) loadMorePosts(); |
| 48 | + }); |
| 49 | + |
| 50 | + const currentTarget = target.current; |
| 51 | + if (currentTarget) observer.observe(currentTarget); |
| 52 | + |
| 53 | + return () => { |
| 54 | + if (currentTarget) observer.unobserve(currentTarget); |
| 55 | + }; |
| 56 | + }, [loadMorePosts]); |
| 57 | + |
| 58 | + return ( |
| 59 | + <div> |
| 60 | + {posts.map(({ id, title, content, author, createdAt }) => { |
| 61 | + const localeCreatedAt = formatToLocaleDate(createdAt); |
| 62 | + return ( |
| 63 | + <PostItem |
| 64 | + key={id} |
| 65 | + linkPostId={id} |
| 66 | + title={title} |
| 67 | + content={content} |
| 68 | + author={author} |
| 69 | + localeCreatedAt={localeCreatedAt} |
| 70 | + /> |
| 71 | + ); |
| 72 | + })} |
| 73 | + <h3 |
| 74 | + ref={target} |
| 75 | + className="mx-8 mb-4 mt-8 text-center text-9xl font-semibold" |
| 76 | + > |
| 77 | + {posts.at(-1)?.id === cursor |
| 78 | + ? '*************더 많은 게시글 로딩 중****************' |
| 79 | + : ''} |
| 80 | + </h3> |
| 81 | + </div> |
| 82 | + ); |
| 83 | +} |
0 commit comments