Skip to content

Commit

Permalink
fix: 같은 상품이 8개씩 중복해서 나옴 (#258)
Browse files Browse the repository at this point in the history
  • Loading branch information
shinhyojeong authored Feb 1, 2024
2 parents 5f5cfba + 35270ad commit af93684
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 64 deletions.
26 changes: 19 additions & 7 deletions src/apis/post/queries.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { InfiniteData, DefaultError } from '@tanstack/react-query'
import { useMutation, useQuery, useInfiniteQuery } from '@tanstack/react-query'
import {
getPost,
Expand All @@ -16,6 +17,7 @@ import type {
UpdatePostReq,
UpdateTradeStatusReq
} from './types'
import type { PostSummaries } from '@types'

export const useCreatePostMutation = () =>
useMutation({
Expand Down Expand Up @@ -81,15 +83,25 @@ export const useGetPostsQuery = (searchOptions: GetPostsReq) =>
enabled: typeof searchOptions.sellerId === 'number'
})

export const useGetInfinitePostsQuery = (params: GetPostsReq) =>
useInfiniteQuery<GetPostsRes>({
queryKey: ['infinitePosts', params],
queryFn: () => getPosts(params),
export const useGetInfinitePostsQuery = ({
limit = 8,
...params
}: GetPostsReq) =>
useInfiniteQuery<
GetPostsRes,
DefaultError,
InfiniteData<PostSummaries, unknown> & { totalPage: number }
>({
queryKey: ['getInfinitePosts', params],
queryFn: ({ pageParam }) =>
getPosts({ ...params, limit, lastId: pageParam as number }),
initialPageParam: null,
getNextPageParam: lastPage =>
lastPage?.hasNext
? lastPage.posts[lastPage.posts.length - 1].id
: undefined
lastPage?.hasNext ? lastPage.posts.at(-1)?.id : undefined,
select: data => ({
...data,
totalPage: data.pages[0].totalCount || 0
})
})

export const useUpdateTradeStatusMutation = () =>
Expand Down
27 changes: 10 additions & 17 deletions src/components/home/ProductList/index.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import { useRouter } from 'next/router'
import type { ReactElement } from 'react'
import { useEffect, useState } from 'react'
import { useEffect } from 'react'
import { useInView } from 'react-intersection-observer'
import { Styled } from './styled'
import type { ProductListProps } from './types'
import { ProductItem } from '../ProductItem'
import { useUpdateLikeStatusMutation } from '@apis/like'

const ProductList = ({
postData,
postList,
hasNextPage,
fetchNextPage
}: ProductListProps): ReactElement => {
const [isFirstRender, setIsFirstRender] = useState<boolean>(false)
const updateLikeStatusMutation = useUpdateLikeStatusMutation()
const router = useRouter()
const { ref: isLastPrdRef, inView } = useInView({

const updateLikeStatusMutation = useUpdateLikeStatusMutation()

const { ref: isLastPostRef, inView } = useInView({
threshold: 1
})

Expand All @@ -26,21 +27,13 @@ const ProductList = ({
}

useEffect(() => {
if (!shouldFetchNextPage) {
return
}
if (!isFirstRender) {
setIsFirstRender(true)
return
}

fetchNextPage && fetchNextPage()
}, [fetchNextPage, shouldFetchNextPage, isFirstRender])
fetchNextPage?.()
}, [fetchNextPage, shouldFetchNextPage])

return (
<>
<Styled.ProductListWrapper>
{postData?.map(page =>
{postList?.map(page =>
page?.posts?.map(post => (
<ProductItem
key={post.id}
Expand All @@ -51,7 +44,7 @@ const ProductList = ({
))
)}
</Styled.ProductListWrapper>
<Styled.LastFooter ref={isLastPrdRef} />
<Styled.LastFooter ref={isLastPostRef} />
</>
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/home/ProductList/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
import type { GetPostsRes } from '@apis/post'

export type ProductListProps = {
postData?: GetPostsRes[]
postList?: GetPostsRes[]
hasNextPage?: boolean
fetchNextPage?(
options?: FetchNextPageOptions
Expand Down
19 changes: 8 additions & 11 deletions src/pages/categories/[categoryCode].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ import { PostSection, ResultHeader } from '@components'
import type { SortOptionCodes, TradeTypeCodes } from '@types'
import { find, removeNullish, toQueryString } from '@utils'

const DEFAULT_PER_PAGE = 8
// TODO: 포스트 전체 갯수 내려달라고 요청해놓았습니다
const POSTS_COUNT_MOCK = 10

type CategoriesProps = {
category?: string
sort?: SortOptionCodes
Expand Down Expand Up @@ -62,12 +58,13 @@ const Categories: NextPage = ({
getCategoriesQuery.data?.map(({ code, name }) => ({ code, name })) || []
const currentCategory = find(categories, { code: searchOptions.category })

const infinitePosts = useGetInfinitePostsQuery({
const getInfinitePostsQuery = useGetInfinitePostsQuery({
lastId: null,
limit: DEFAULT_PER_PAGE,
...searchParams
})

const postCount = getInfinitePostsQuery.data?.totalPage || 0

const searchByCategory = ({
category,
priceRange,
Expand Down Expand Up @@ -96,16 +93,16 @@ const Categories: NextPage = ({
<Layout>
<ResultWrapper>
<ResultHeader
postsCount={POSTS_COUNT_MOCK}
postsCount={postCount}
resultMessage={currentCategory?.name || '전체'}
/>
<PostSection
infinitePosts={{
fetchNextPage: infinitePosts?.fetchNextPage,
hasNextPage: infinitePosts?.hasNextPage,
postData: infinitePosts.data?.pages
fetchNextPage: getInfinitePostsQuery?.fetchNextPage,
hasNextPage: getInfinitePostsQuery?.hasNextPage,
postList: getInfinitePostsQuery.data?.pages
}}
postsCount={POSTS_COUNT_MOCK}
postsCount={postCount}
searchOptions={searchOptions}
onChangeSearchOption={handleChangeSearchOptions}
/>
Expand Down
26 changes: 10 additions & 16 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,26 @@ import { ProductList } from '../components/home/ProductList'
import { useGetInfinitePostsQuery } from '@apis/post'
import { CategorySlider, HomeBanner } from '@components'

const DEFAULT_PER_PAGE = 8
// TODO: 포스트 전체 갯수 내려달라고 요청해놓았습니다
const POSTS_COUNTS_MOCK = 10

const Home: NextPage = () => {
const {
data: postList,
fetchNextPage,
hasNextPage
} = useGetInfinitePostsQuery({
lastId: null,
limit: DEFAULT_PER_PAGE
})
const router = useRouter()

const getInfinitePostsQuery = useGetInfinitePostsQuery({
lastId: null
})

const postCount = getInfinitePostsQuery.data?.totalPage || 0

return (
<Layout>
<HomeWrapper>
<HomeBanner />
<CategorySlider />
<ProductTitle>새로운 상품</ProductTitle>
{POSTS_COUNTS_MOCK > 0 ? (
{postCount > 0 ? (
<ProductList
fetchNextPage={fetchNextPage}
hasNextPage={hasNextPage}
postData={postList?.pages}
fetchNextPage={getInfinitePostsQuery.fetchNextPage}
hasNextPage={getInfinitePostsQuery.hasNextPage}
postList={getInfinitePostsQuery.data?.pages}
/>
) : (
<Placeholder>
Expand Down
23 changes: 11 additions & 12 deletions src/pages/result/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ import { ResultHeader, PostSection } from '@components'
import type { SortOptionCodes, TradeTypeCodes } from '@types'
import { toQueryString, removeNullish } from '@utils'

const DEFAULT_PER_PAGE = 8
// TODO: 포스트 전체 갯수 내려달라고 요청해놓았습니다
const POST_COUNT_MOCK = 10

type ResultPageProps = {
keyword?: string
category?: string | null
Expand Down Expand Up @@ -47,11 +43,13 @@ const ResultPage: NextPage = ({
tradeType
}: ResultPageProps) => {
const router = useRouter()
const searchKeyword = useAtomValue(searchKeywordAtom)
const [searchOptions, setSearchOptions] = useState<SearchOptionsState>({
sort: 'CREATED_DATE_DESC',
priceRange: {}
})

const searchKeyword = useAtomValue(searchKeywordAtom)

const currentKeyword = searchKeyword ?? keyword
const searchParams = removeNullish({
category: searchOptions?.category ?? category,
Expand All @@ -62,12 +60,13 @@ const ResultPage: NextPage = ({
searchKeyword: currentKeyword
})

const infinitePosts = useGetInfinitePostsQuery({
const getInfinitePostsQuery = useGetInfinitePostsQuery({
lastId: null,
limit: DEFAULT_PER_PAGE,
...searchParams
})

const postCount = getInfinitePostsQuery.data?.totalPage || 0

const searchByResult = ({ priceRange, ...params }: SearchOptionsState) => {
router.push(
`/result?${toQueryString({
Expand All @@ -92,16 +91,16 @@ const ResultPage: NextPage = ({
<Layout>
<ResultWrapper>
<ResultHeader
postsCount={POST_COUNT_MOCK}
postsCount={postCount}
resultMessage={`"${currentKeyword}"의 검색결과`}
/>
<PostSection
infinitePosts={{
fetchNextPage: infinitePosts?.fetchNextPage,
hasNextPage: infinitePosts?.hasNextPage,
postData: infinitePosts.data?.pages
fetchNextPage: getInfinitePostsQuery?.fetchNextPage,
hasNextPage: getInfinitePostsQuery?.hasNextPage,
postList: getInfinitePostsQuery.data?.pages
}}
postsCount={POST_COUNT_MOCK}
postsCount={postCount}
searchOptions={searchOptions}
onChangeSearchOption={handleChangeSearchOptions}
/>
Expand Down
1 change: 1 addition & 0 deletions src/types/scheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export type PostSummary = {
hasReview: boolean
}
export type PostSummaries = {
totalCount: number
posts: PostSummary[]
hasNext: boolean
}
Expand Down

0 comments on commit af93684

Please sign in to comment.