Notice
Recent Posts
Recent Comments
Link
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

[react-project] onscroll 스크롤 이벤트 사용하여 무한 스크롤 구현하기 본문

Project

[react-project] onscroll 스크롤 이벤트 사용하여 무한 스크롤 구현하기

보람- 2023. 12. 19. 17:16

 

const Main = () => {
  const [data, setData] = useState({});
  const [board, setBoard] = useState([]);
  const [page, setPage] = useState(false);

  useEffect(() => {
    if (!data.boards) {
      const boardData = async () => {
        try {
          const response = await axios.get(
            `${process.env.REACT_APP_API_SERVER}/page/1`
          );
          setData(response.data);
          setBoard(response.data.boards);
          setPage(response.data.nextPage);
        } catch (error) {
          console.log(`error :`, error);
        }
      };
      boardData();
    }

    const scroll = async () => {
      try {
        const height = document.documentElement.scrollTop + window.innerHeight;
        const scrollPosition = document.documentElement.scrollHeight;
        if (height >= scrollPosition * 0.8) {
          const response = await axios.get(
            `${process.env.REACT_APP_API_SERVER}/page/${page}`
          );
          setBoard([...board, ...response.data.boards]);
          setPage(response.data.nextPage);
          document.onscroll = null;
        }
      } catch (error) {
        console.log(`error :`, error);
      }
    };
    if (page) document.onscroll = scroll;
    return () => {
      document.onscroll = null;
    };
  }, [page]);

  return (
    <>
      <div className="flex w-full items-stretch">
        <Sidebar />
        <MainContent board={board} />
        <ChatContent />
      </div>
    </>
  );
};

 

- 페이지에서(main, search, tagItem) /page/1로 요청을 해서 10개의 게시글을 보여주고

- 스크롤이 80% 내려왔을때 다음 페이지  /page/2  추가 데이터 요청하기

  - 다음페이지가 있다면 setPage(response.data.nextPage) 없다면 false

 

- page가 변했다면 scroll 함수가 작동하고,

- scroll 이벤트가 실행되어 스크롤이 80% 내려왔다면 서버에 요청을 보내고

- onscroll = null값을 주어 이벤트를 멈추게하고

- 다시 setPage가 업데이트 되면 다시 scroll 함수 작동하는 구조

→ page 값이 변할때마다 useEffect가 실행되게 배열안에 page를 넣어준다. 

 

 

 

 


※ react query 배워서 다시 만들어보기