-
Notifications
You must be signed in to change notification settings - Fork 5
Feature/my-profile api 연결 및 무한 스크롤 훅 생성 #77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
2e70d00
feat: review, wine 데이터 타입 정의
youdaeng2 be881dc
feat: 내 리뷰·내 와인 조회 API 함수(getMyReviews, getMyWines) 추가
youdaeng2 88134eb
feat: 리뷰·와인 리스트 페이지 API 연동
youdaeng2 a57d2a0
feat: 와인, 리뷰 타입 정의 수정
youdaeng2 87c1d7f
refactor: 와인, 리뷰리스트 api 호출 코드 수정(axios 인터셉터에 맞게)
youdaeng2 dc604e9
feat: 무한스크롤 훅(observer 기반) 생성 및 리스트 컴포넌트 연결
youdaeng2 67495b2
feat: next.config에 이미지 도메인 추가
youdaeng2 4df8b14
chore: 목업데이터 삭제
youdaeng2 fee88f2
feat: Tab에 표시되는 총 개수 실 api와 연결(상태로 관리, 리스트에서 데이터 올려줌)
youdaeng2 f35c21d
Merge branch 'dev' into feature/myprofile-api
youdaeng2 109f1f4
choer: my-profile 네이밍 변경
youdaeng2 f1f6a31
choer: my-profile 네이밍 변경에 맞춰 경로 수정 (my-profile/index 및 Gnb)
youdaeng2 b76a332
Merge branch 'dev' into feature/myprofile-api
youdaeng2 8e85d43
chore: next.config 이미지 도메인 중복 코드 제거
youdaeng2 387ec13
Merge branch 'dev' into feature/myprofile-api
youdaeng2 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import apiClient from '@/api/apiClient'; | ||
|
|
||
| import type { MyReviewsResponse } from '@/types/MyReviewsTypes'; | ||
|
|
||
| const DEFAULT_LIMIT = 10; | ||
| const BASE_PATH = '/users/me/reviews'; | ||
|
|
||
| /** | ||
| * 내 리뷰 조회 옵션 | ||
| */ | ||
| export interface FetchMyReviewsOptions { | ||
| /** 조회 시작 커서 (기본: 0) */ | ||
| cursor?: number | null; | ||
| /** 한 페이지당 아이템 수 (기본: DEFAULT_LIMIT) */ | ||
| limit?: number; | ||
| } | ||
|
|
||
| /** | ||
| * 내 리뷰 목록 가져오기 | ||
| * | ||
| * @param options.cursor 시작 커서 (기본 0) | ||
| * @param options.limit 페이지 크기 (기본 DEFAULT_LIMIT) | ||
| * @returns Promise<MyReviewsResponse> | ||
| * @throws {Error} NEXT_PUBLIC_TEAM 환경변수가 없으면 예외 발생 | ||
| */ | ||
| export const getMyReviews = async ( | ||
| options: FetchMyReviewsOptions = {}, | ||
| ): Promise<MyReviewsResponse> => { | ||
| const { cursor = 0, limit = DEFAULT_LIMIT } = options; | ||
|
|
||
| const teamId = process.env.NEXT_PUBLIC_TEAM; | ||
| if (!teamId) { | ||
| throw new Error('환경변수 NEXT_PUBLIC_TEAM이 설정되지 않았습니다. 빌드 환경을 확인해주세요.'); | ||
| } | ||
|
|
||
| const url = `/${teamId}${BASE_PATH}`; | ||
|
|
||
| // API 호출 | ||
| const response = await apiClient.get<MyReviewsResponse, MyReviewsResponse>(url, { | ||
| params: { cursor, limit }, | ||
| }); | ||
|
|
||
| // 요청 디버그 로그 (개발 환경에서만 활성화 권장) | ||
| if (process.env.NODE_ENV === 'development') { | ||
| console.debug('[API] getMyReviews', { url, cursor, limit, response }); | ||
| } | ||
|
|
||
| return response; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import apiClient from '@/api/apiClient'; | ||
|
|
||
| import type { MyWinesResponse } from '@/types/MyWinesTypes'; | ||
|
|
||
| const DEFAULT_LIMIT = 10; | ||
| const BASE_PATH = '/users/me/wines'; | ||
|
|
||
| /** | ||
| * 내 와인 조회 옵션 | ||
| */ | ||
| export interface FetchMyWinesOptions { | ||
| /** 조회 시작 커서 (기본: 0) */ | ||
| cursor?: number | null; | ||
| /** 한 페이지당 아이템 수 (기본: DEFAULT_LIMIT) */ | ||
| limit?: number; | ||
| } | ||
|
|
||
| /** | ||
| * 내 와인 목록 가져오기 | ||
| * | ||
| * @param options.cursor 시작 커서 (기본 0) | ||
| * @param options.limit 페이지 크기 (기본 DEFAULT_LIMIT) | ||
| * @returns Promise<MyWinesResponse> | ||
| * @throws {Error} NEXT_PUBLIC_TEAM 환경변수가 없으면 예외 발생 | ||
| */ | ||
| export const getMyWines = async (options: FetchMyWinesOptions = {}): Promise<MyWinesResponse> => { | ||
| const { cursor = 0, limit = DEFAULT_LIMIT } = options; | ||
|
|
||
| const teamId = process.env.NEXT_PUBLIC_TEAM; | ||
| if (!teamId) { | ||
| throw new Error('환경변수 NEXT_PUBLIC_TEAM이 설정되지 않았습니다. 빌드 환경을 확인해주세요.'); | ||
| } | ||
|
|
||
| const url = `/${teamId}${BASE_PATH}`; | ||
|
|
||
| // API 호출 | ||
| const response = await apiClient.get<MyWinesResponse, MyWinesResponse>(url, { | ||
| params: { cursor, limit }, | ||
| }); | ||
|
|
||
| // 요청 디버그 로그 | ||
| if (process.env.NODE_ENV === 'development') { | ||
| console.debug('[API] getMyWines', { url, cursor, limit, response }); | ||
| } | ||
|
|
||
| return response; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import React, { useEffect, useRef } from 'react'; | ||
|
|
||
| import { useInfiniteQuery } from '@tanstack/react-query'; | ||
|
|
||
| import { getMyReviews } from '@/api/myReviews'; | ||
| import DotIcon from '@/assets/icons/dot.svg'; | ||
| import { MyCard } from '@/components/common/card/MyCard'; | ||
| import MenuDropdown from '@/components/common/dropdown/MenuDropdown'; | ||
| import { Badge } from '@/components/ui/badge'; | ||
| import { useInfiniteScroll } from '@/hooks/useInfiniteScroll'; | ||
| import { MyReview } from '@/types/MyReviewsTypes'; | ||
|
|
||
| const PAGE_LIMIT = 10; | ||
|
|
||
| interface ReviewListProps { | ||
| setTotalCount: (count: number) => void; | ||
| } | ||
| /** | ||
| * ReviewList 컴포넌트 | ||
| * | ||
| * 무한 스크롤을 통해 사용자의 리뷰 목록을 페이징하여 불러옴 | ||
| * IntersectionObserver로 스크롤 끝에 도달 시 다음 페이지를 자동으로 로드 | ||
| * | ||
| */ | ||
| export function ReviewList({ setTotalCount }: ReviewListProps) { | ||
| const observerRef = useRef<HTMLDivElement | null>(null); | ||
|
|
||
| // useInfiniteQuery 훅으로 리뷰 데이터를 무한 스크롤 형태로 조회 | ||
| const { data, isLoading, isError, fetchNextPage, hasNextPage, isFetchingNextPage } = | ||
| useInfiniteQuery({ | ||
| queryKey: ['myReviews'], | ||
| queryFn: ({ pageParam = 0 }) => getMyReviews({ cursor: pageParam, limit: PAGE_LIMIT }), | ||
| initialPageParam: 0, | ||
| getNextPageParam: (lastPage) => lastPage.nextCursor ?? null, | ||
| }); | ||
| // xhx | ||
| useEffect(() => { | ||
| if (data?.pages?.[0]?.totalCount != null) { | ||
| setTotalCount(data.pages[0].totalCount); | ||
| } | ||
| }, [data, setTotalCount]); | ||
|
|
||
| // IntersectionObserver 훅 적용으로 스크롤 끝 감지 | ||
| useInfiniteScroll({ | ||
| targetRef: observerRef, | ||
| hasNextPage, | ||
| fetchNextPage, | ||
| isFetching: isFetchingNextPage, | ||
| }); | ||
|
|
||
| // 로딩 및 에러 상태 처리 (임시) | ||
| if (isLoading) return <p>불러오는 중…</p>; | ||
| if (isError) return <p>불러오기 실패</p>; | ||
| if (!data) return <p>리뷰 데이터가 없습니다.</p>; | ||
|
|
||
| // 리뮤 목록 평탄화 | ||
| const reviews: MyReview[] = data?.pages?.flatMap((page) => page.list ?? []) ?? []; | ||
|
|
||
| return ( | ||
| <div className='space-y-4 mt-4'> | ||
| {reviews.map((review) => ( | ||
| <MyCard | ||
| key={review.id} | ||
| rating={ | ||
| <Badge variant='star'> | ||
| <span className='inline-block w-full h-full pt-[2px]'> | ||
| ★ {review.rating.toFixed(1)} | ||
| </span> | ||
| </Badge> | ||
| } | ||
| timeAgo={new Date(review.createdAt).toLocaleDateString()} | ||
| title={review.user.nickname} | ||
| review={review.content} | ||
| rightSlot={ | ||
| <MenuDropdown | ||
| trigger={ | ||
| <button className='w-6 h-6 text-gray-500 hover:text-primary transition-colors'> | ||
| <DotIcon /> | ||
| </button> | ||
| } | ||
| options={[ | ||
| { label: '수정하기', value: 'edit' }, | ||
| { label: '삭제하기', value: 'delete' }, | ||
| ]} | ||
| onSelect={(value) => console.log(`${value} clicked: review id=${review.id}`)} | ||
| /> | ||
| } | ||
| /> | ||
| ))} | ||
| {/* 옵저버 감지 요소 */} | ||
| <div ref={observerRef} className='w-1 h-1' /> | ||
| </div> | ||
| ); | ||
| } |
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| import React, { useEffect, useRef } from 'react'; | ||
|
|
||
| import { useInfiniteQuery } from '@tanstack/react-query'; | ||
|
|
||
| import { getMyWines } from '@/api/myWines'; | ||
| import DotIcon from '@/assets/icons/dot.svg'; | ||
| import { ImageCard } from '@/components/common/card/ImageCard'; | ||
| import MenuDropdown from '@/components/common/dropdown/MenuDropdown'; | ||
| import { Badge } from '@/components/ui/badge'; | ||
| import { useInfiniteScroll } from '@/hooks/useInfiniteScroll'; | ||
|
|
||
| import type { MyWine, MyWinesResponse } from '@/types/MyWinesTypes'; | ||
|
|
||
| const PAGE_LIMIT = 10; | ||
| interface WineListProps { | ||
| setTotalCount: (count: number) => void; | ||
| } | ||
| /** | ||
| * WineList 컴포넌트 | ||
| * | ||
| * 무한 스크롤을 통해 사용자의 와인 목록을 페이징하여 불러옴 | ||
| * IntersectionObserver로 스크롤 끝에 도달 시 추가 페이지를 자동으로 로드 | ||
| * | ||
| */ | ||
| export function WineList({ setTotalCount }: WineListProps) { | ||
| const observerRef = useRef<HTMLDivElement | null>(null); | ||
|
|
||
| //useInfiniteQuery 훅으로 와인 데이터를 무한 스크롤 형태로 조회 | ||
| const { data, isLoading, isError, fetchNextPage, hasNextPage, isFetchingNextPage } = | ||
| useInfiniteQuery({ | ||
| queryKey: ['myWines'], | ||
| queryFn: ({ pageParam = 0 }) => getMyWines({ cursor: pageParam, limit: PAGE_LIMIT }), | ||
| initialPageParam: 0, | ||
| getNextPageParam: (lastPage: MyWinesResponse | undefined) => lastPage?.nextCursor ?? null, | ||
| }); | ||
|
|
||
| useEffect(() => { | ||
| if (data?.pages?.[0]?.totalCount != null) { | ||
| setTotalCount(data.pages[0].totalCount); | ||
| } | ||
| }, [data, setTotalCount]); | ||
|
|
||
| // IntersectionObserver 훅 적용으로 스크롤 끝 감지 | ||
| useInfiniteScroll({ | ||
| targetRef: observerRef, | ||
| hasNextPage: !!hasNextPage, | ||
| fetchNextPage, | ||
| isFetching: isFetchingNextPage, | ||
| }); | ||
|
|
||
| // 로딩 및 에러 상태 처리 (임시) | ||
| if (isLoading) return <p className='text-center py-4'>와인 불러오는 중…</p>; | ||
| if (isError || !data) return <p className='text-center py-4'>와인 불러오기 실패</p>; | ||
|
|
||
| // 와인 목록 평탄화 | ||
| const wines: MyWine[] = data?.pages?.flatMap((page) => page?.list ?? []) ?? []; | ||
|
|
||
| return ( | ||
| <div className='flex flex-col mt-9 space-y-9 md:space-y-16 md:mt-16'> | ||
| {wines.map((wine) => ( | ||
| <ImageCard | ||
| key={wine.id} | ||
| className='relative pl-24 min-h-[164px] md:min-h-[228px] md:pl-44 md:pt-10' | ||
| imageSrc={wine.image} | ||
| imageClassName='object-contain absolute left-3 bottom-0 h-[185px] md:h-[270px] md:left-12' | ||
| rightSlot={ | ||
| <MenuDropdown | ||
| trigger={ | ||
| <button className='w-6 h-6 text-gray-500 hover:text-primary transition-colors'> | ||
| <DotIcon /> | ||
| </button> | ||
| } | ||
| options={[ | ||
| { label: '수정하기', value: 'edit' }, | ||
| { label: '삭제하기', value: 'delete' }, | ||
| ]} | ||
| onSelect={(value) => console.log(`${value} clicked for wine id: ${wine.id}`)} | ||
| /> | ||
| } | ||
| > | ||
| <div className='flex flex-col items-start justify-center h-full'> | ||
| <h4 className='text-xl/6 font-semibold text-gray-800 mb-4 md:text-3xl md:mb-5'> | ||
| {wine.name} | ||
| </h4> | ||
| <p className='custom-text-md-legular text-gray-500 mb-2 md:custom-text-lg-legular md:mb-4'> | ||
| {wine.region} | ||
| </p> | ||
| <Badge variant='priceBadge'> | ||
| <span className='inline-block w-full h-full pt-[3px]'> | ||
| ₩ {wine.price.toLocaleString()} | ||
| </span> | ||
| </Badge> | ||
| </div> | ||
| </ImageCard> | ||
| ))} | ||
| {/* 옵저버 감지 요소 */} | ||
| <div ref={observerRef} className='w-1 h-1' /> | ||
| </div> | ||
| ); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
인피니티 쿼리를 쓰면 이렇게 쓰는 거군요.
패칭함수를 따로 콜백으로 넘겨줘야할 것 같다고 생각하고 있었는데
인피티니 쿼리랑 같이 쓰니까 간결하고 좋네요