강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của hanumoka
hanumoka

câu hỏi đã được viết

Phát triển blog công nghệ với Gatsby dựa trên React

Cách tạo kiểu cho các thành phần bằng thư viện EmotionJS

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

Viết

·

379

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

 

Gatsbyblog

Câu trả lời 1

1

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

Hình ảnh hồ sơ của hanumoka
hanumoka

câu hỏi đã được viết

Đặt câu hỏi