Skip to content

Commit

Permalink
feat: 소식페이지 무한스크롤을 위한 API 훅 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
hjy0951 committed Aug 27, 2024
1 parent 490f921 commit 748fd30
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
13 changes: 13 additions & 0 deletions app/api/news/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NextRequest, NextResponse } from 'next/server';

import { fetchData } from '@/apis/fetch-data';
import { NewsResponse } from '@/features/news';

export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const cursorId = searchParams.get('cursorId');
const queryString = cursorId ? `?cursorId=${cursorId}` : '';
const data = await fetchData<NewsResponse>(`/news${queryString}`, 'GET');

return NextResponse.json(data);
}
1 change: 1 addition & 0 deletions features/news/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './use-news-data';
25 changes: 25 additions & 0 deletions features/news/hooks/use-news-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useInfiniteQuery } from '@tanstack/react-query';

import { NewsResponse } from '../types';

const getNewsData = async (cursorId: unknown) => {
const queryString = cursorId ? `?cursorId=${cursorId as string}` : '';
const res = await fetch(`/api/news${queryString}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});

return res.json();
};

export const useNewsData = () => {
return useInfiniteQuery<NewsResponse>({
queryKey: ['newsData'],
queryFn: ({ pageParam = undefined }) => getNewsData(pageParam),
initialPageParam: null,
getNextPageParam: (lastPage) =>
lastPage.data.hasNext ? lastPage.data.cursorId : undefined,
});
};
10 changes: 9 additions & 1 deletion features/news/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { Response } from '@/apis';
import { TimeLineContent } from '@/features/main';

import { NewsItemWrapperProps } from '../components';

export type NewsItem = TimeLineContent & NewsItemWrapperProps;
export type NewsContent = TimeLineContent & NewsItemWrapperProps;

export type NewsResponse = Response<{
content: Array<NewsContent>;
pageSize: number;
cursorId: number;
hasNext: boolean;
}>;

0 comments on commit 748fd30

Please sign in to comment.