• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

IntersectionObserver deploy( gatsby build) 시 오류(자답)

22.10.30 18:20 작성 조회수 213

1

useInfiniteScroll.tsx 파일

IntersectionObserver 구문에서 오류 발생

아래 처럼 코드 수정

import { MutableRefObject, useState, useEffect, useRef, useMemo } from 'react'
import { PostListItemType } from 'types/PostItem.types'

export type useInfiniteScrollType = {
  containerRef: MutableRefObject<HTMLDivElement | null>
  postList: PostListItemType[]
}

const NUMBER_OF_ITEMS_PER_PAGE = 10

const useInfiniteScroll = function (
  selectedCategory: string,
  posts: PostListItemType[],
): useInfiniteScrollType {
  const containerRef: MutableRefObject<HTMLDivElement | null> = useRef<HTMLDivElement>(
    null,
  )
  const [count, setCount] = useState<number>(1)

  const postListByCategory = useMemo<PostListItemType[]>(
    () =>
      posts.filter(({ node: { frontmatter: { categories } } }: PostListItemType) =>
        selectedCategory !== 'All'
          ? categories.includes(selectedCategory)
          : true,
      ),
    [selectedCategory],
  )

  const observer = useRef<IntersectionObserver | null>(null);

  useEffect(() => {
    observer.current = new IntersectionObserver(
      (entries, observer) => {
        if (!entries[0].isIntersecting) return;

        setCount(value => value + 1);
        observer.disconnect();
      },
    )
  }, []);

  useEffect(() => setCount(1), [selectedCategory])

  useEffect(() => {
    if (
      NUMBER_OF_ITEMS_PER_PAGE * count >= postListByCategory.length ||
      containerRef.current === null ||
      containerRef.current.children.length === 0
    ){
      return;
    }

    if(observer && observer.current){
      observer.current.observe(
        containerRef.current.children[containerRef.current.children.length - 1],
      )
    }

  }, [count, selectedCategory, observer])

  return {
    containerRef,
    postList: postListByCategory.slice(0, count * NUMBER_OF_ITEMS_PER_PAGE),
  }
}

export default useInfiniteScroll

 

답변 1

답변을 작성해보세요.

1

yunseong3736님의 프로필

yunseong3736

2023.04.07

Gatsby cloud에 배포할 때도 이 부분이 필요합니다. 감사합니다.