Skip to content
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

feat: infinite scroll just working on frontend bottomsheet #136

Merged
merged 2 commits into from
Sep 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions src/app/map/[mapId]/place-list-bottom-sheet.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

import { forwardRef, Fragment, useEffect, useState } from 'react'
import { forwardRef, useEffect, useState } from 'react'

import type { FilterIdsType } from './page'

Expand All @@ -11,6 +11,7 @@ import PlaceListItem from '@/components/place/place-list-item'
import useFetch from '@/hooks/use-fetch'
import { APIError } from '@/models/api/index'
import type { PlaceType } from '@/models/api/place'
import { useInfiniteScroll } from '@/hooks/use-infinite-scroll'
import { api } from '@/utils/api'

interface PlaceListBottomSheetProps {
Expand Down Expand Up @@ -38,6 +39,11 @@ const PlaceListBottomSheet = forwardRef<
(selectedFilter?.category !== 'all' ? 1 : 0) +
(selectedFilter?.tags.length ?? 0)

const { data: slicedPlaceList, listRef } = useInfiniteScroll<PlaceType>({
totalData: placeList,
itemsPerPage: 10,
})

const getIsLike = (place: PlaceType): boolean => {
if (typeof userId === 'undefined') return false

Expand Down Expand Up @@ -119,17 +125,20 @@ const PlaceListBottomSheet = forwardRef<
필터
</FilterButton>
</div>
{placeList.length > 0 ? (
<div className="no-scrollbar flex-1 overflow-y-scroll overscroll-contain px-5">
{slicedPlaceList.length > 0 ? (
<div
ref={listRef}
className="no-scrollbar flex-1 overflow-y-scroll overscroll-contain px-5"
>
<ul
ref={(element) => {
if (typeof ref !== 'function' && ref?.current) {
ref.current[1] = element as HTMLUListElement
}
}}
>
{placeList.map((place) => (
<Fragment key={`bottom-sheet-${place.place.kakaoPlace.id}`}>
{slicedPlaceList.map((place, index) => (
<li key={`bottom-sheet-${place.place.kakaoPlace.id}-${index}`}>
<PlaceListItem
placeId={place.place.kakaoPlace.id}
address={place.place.kakaoPlace.address}
Expand All @@ -153,7 +162,7 @@ const PlaceListBottomSheet = forwardRef<
className="first:pt-1"
/>
<hr className="my-[2px] h-[1px] border-0 bg-neutral-600 last:hidden" />
</Fragment>
</li>
))}
</ul>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/place/place-list-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const PlaceListItem = ({
<ProxyImage
key={`${placeId}-${image}-${index}`}
src={image}
className="aspect-square w-[calc(33.4%-8px)] rounded-md object-cover"
className="aspect-square w-[calc(33.4%-8px)] min-w-[calc(33.4%-8px)] rounded-md object-cover"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앗 min 감쟈!

alt={`${name}${index}`}
/>
))}
Expand Down
70 changes: 70 additions & 0 deletions src/hooks/use-infinite-scroll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import debounce from 'lodash.debounce'
import { useState, useEffect, useCallback, useRef } from 'react'

interface UseInfiniteScrollProps<T> {
totalData: T[]
itemsPerPage: number
threshold?: number
}

const INITIAL_PAGE = 1

export const useInfiniteScroll = <T extends any>({
totalData,
itemsPerPage,
threshold = 100,
}: UseInfiniteScrollProps<T>) => {
const [data, setData] = useState<T[]>(totalData.slice(0, itemsPerPage))
const [page, setPage] = useState(INITIAL_PAGE)
const [isLoading, setIsLoading] = useState(false)
const [hasMore, setHasMore] = useState(totalData.length > itemsPerPage)
const listRef = useRef<HTMLDivElement | null>(null)

const loadMoreData = useCallback(() => {
if (isLoading || !hasMore) return

setIsLoading(true)
setTimeout(() => {
const startIndex = page * itemsPerPage
const endIndex = startIndex + itemsPerPage
const newData = totalData.slice(startIndex, endIndex)

if (newData.length === 0) {
setHasMore(false)
} else {
setData((prevData) => [...prevData, ...newData])
setPage((prevPage) => prevPage + 1)
}

setIsLoading(false)
}, 100)
}, [page, itemsPerPage, totalData, isLoading, hasMore])

const handleScroll = useCallback(() => {
if (!listRef.current) return

const { scrollTop, scrollHeight, clientHeight } = listRef.current
if (
scrollHeight - scrollTop <= clientHeight + threshold &&
!isLoading &&
hasMore
) {
loadMoreData()
}
}, [isLoading, hasMore, loadMoreData, threshold])

useEffect(() => {
const ref = listRef.current
if (!ref) return

const debouncedHandleScroll = debounce(handleScroll, 300)

ref.addEventListener('scroll', debouncedHandleScroll)

return () => {
ref.removeEventListener('scroll', debouncedHandleScroll)
}
}, [handleScroll])

return { data, isLoading, listRef }
}
Loading