Programming

[TIL] Infinite Scorll(react-query)

jay-dev 2023. 8. 1. 09:09

Infinite Scroll Error

첫 화면 렌더링시
메인 페이지 - 이미지가 일부 깨져보이는 현상 발생
프로필 페이지 - 일부 스켈레톤 UI가 새로고침 전까지 잔류하는 현상 발생

### Temporary Solution

navigate로 설정된 url이동(페이지 리로딩 x)을
window.location.href를 활용하여 페이지 리로딩하여 오류 수정

 

window.location.href = '/main';



### Advanced Solution

react-query useInfiniteQuery와 observer pattern을 활용하여 infinite scroll 구현
useInfiniteQuery에 내장된 isLoading → isFetching으로 코드 변경하여 오류 수정

 

 const { data, isSuccess, fetchNextPage, hasNextPage, isFetching, isError } = useInfiniteQuery(
    'mainPosts',
    ({ pageParam = 1 }) => getPosts(pageParam),
    {
      getNextPageParam: (posts) => {
        return posts.last ? undefined : posts.pageable.pageNumber + 2;
      },
    }
  );

      <MainHeader>
        {isFetching &&
          Array(3)
            .fill()
            .map((_, index) => <PostSkeleton key={index} />)}
        {data && allPosts.map((post) => <MainPost key={post.postId} post={post} />)}
        <div ref={observerElem}></div>
      </MainHeader>