feat: 자유게시판 무한스크롤 추가

This commit is contained in:
jhynsoo 2024-08-11 23:01:32 +09:00
parent f20bd2dd51
commit ba592a8a19
2 changed files with 24 additions and 14 deletions

View File

@ -1,10 +1,17 @@
import { useSuspenseQuery } from '@tanstack/react-query';
import { useSuspenseInfiniteQuery } from '@tanstack/react-query';
import instance from '../../utils/axios/instance';
import { API_URL } from '../../constants';
import { API_URL, PAGE_SIZE } from '../../constants';
export function useFreeboards(lectureId, page = 0) {
return useSuspenseQuery({
return useSuspenseInfiniteQuery({
queryKey: ['freeboardlist', lectureId, page],
queryFn: () => instance.get(`${API_URL}/board?lectureId=${lectureId}&category=freeboard&pageNo=${page}`),
queryFn: ({ pageParam = 0 }) =>
instance.get(`${API_URL}/board?lectureId=${lectureId}&category=freeboard&pageNo=${pageParam}`),
getNextPageParam: (lastPage, allPages) => {
if (lastPage.data.length < PAGE_SIZE) {
return undefined;
}
return allPages.length + 1;
},
});
}

View File

@ -2,25 +2,28 @@ import { ArticleLink } from '../../components/ArticleLink';
import ArticleBoard from '../../components/ArticleBoard/ArticleBoard';
import { useFreeboards } from '../../hooks/api/useFreeboards';
import { useParams } from 'react-router-dom';
import IntersectionArea from '../../components/IntersectionArea/IntersectionObserver';
export default function NoticeListPage() {
const { lectureId } = useParams();
const { data } = useFreeboards(lectureId);
const notices = data?.data;
const { data, fetchNextPage, hasNextPage } = useFreeboards(lectureId);
const articles = data?.pages.flatMap((page) => page.data);
return (
<ArticleBoard
title="자유게시판"
canCreate={true}
>
{notices.map?.((notice) => (
<ArticleLink
key={`${notice.id}`}
title={notice.title}
sub={`${new Date(notice.createdAt).toLocaleDateString()} ${new Date(notice.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`}
to={`${notice.id}`}
/>
))}
{articles.length &&
articles.map?.((notice) => (
<ArticleLink
key={`${notice.id}`}
title={notice.title}
sub={`${new Date(notice.createdAt).toLocaleDateString()} ${new Date(notice.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`}
to={`${notice.id}`}
/>
))}
{hasNextPage && <IntersectionArea onObserve={() => fetchNextPage()} />}
</ArticleBoard>
);
}