2nd Project 기억하고 싶은 코드 (2)

LEE JIYUN·2020년 8월 9일
0

2ndProject

목록 보기
2/3

Offset & Limit을 이용한 Pagination

 const fetchData = (api, setData, data) => {
   // API주소, 데이터, 데이터함수를 인자로 전달 받아
    setLoading(true);
    fetch(
      `${TopicCardsAPI}/photo${api}offset=${offset}&limit=${LIMIT}`,
      /* access token가 있다면 header에 담아서 API를 호출
         offset : page & limit : images per page */
      accessToken && {
        headers: {
          Authorization: accessToken,
        },
      }
    )
      .then((res) => res.json())
      .then((res) => {
        data 
         ? setData([...data, ...res.data]) 
      /* 데이터가 있다면 (이미 한 번 렌더가 된 경우) 
         해당 데이터 뒤에 위에서 받은 데이터를 추가하고 */
         : setData([...res.data]);
      /* 데이터가 없다면 (렌더된 데이터가 없는 경우) 
         위에서 받은 데이터를 빈 배열에 담는다 */
        setLoading(false);
      });
  };

Scroll at Bottom?

 console.log("window.innerHeight 일정함 윈도우에 보이는 높이", window.innerHeight);
 console.log("window.scrollY Y축 스크롤의 높이 ", window.scrollY);
 console.log("document.body.offsetHeight document.body의 높이", document.body.offsetHeight);

 window.onscroll = function () {
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        alert("Bottom!")
      }
    };

Intersection Observer

Unsplash 이미지 목록을 scroll하면 하단에 로드 되지 않은 이미지의 BackgroundColor가 먼저 render되는 것을 확인할 수 있다. Skeleton을 이용하면 될 것 같았는데, scroll 위치에 따라 새로 fetch되는 요소들에만 skeleton을 적용하는 방법을 찾지 못해 이번 프로젝트에서는 대신 Intersection Observer를 이용하여 scroll을 내렸을 때 화면 노출 여부에 따라 BackgroundColor를 표시 후 이미지를 표시하기로 했다.

// 먼저 IntersectionObserver 객체를 생성한다.
const observer = new IntersectionObserver(funct, options)

여기 들어갈 function과 option을 보자.

/* 먼저 option이다. 이 조건에 부합할 시 함수가 실행된다. 
   threshold는 문지방, 즉 요소의 화면 노출 퍼센티지라고 보면 된다. */
const options = { threshold: 0.5 }; 
/* 아래는 function이다. 인자로 전달되는 entries는 배열이다.
   Target Element가 options의 조건을 충족할 때, 
   즉 여기서는 100% 노출되었을 때 ( threshold: 1.0 ) 
   해당 element를 entries 배열에 추가하고 funct 함수를 호출한다. */
const funct = (entries, observer) => {
      entries.forEach((entry) => {
 /* 함수가 호출되면 isIntersecting으로 각 요소의 화면 노출 여부를 확인한다.
    만약 화면에 노출되어있다면 해당 요소를 Observe Target에서 제외하고,
    backgroundColor 에 target의 color를 적용한다.
*/
        if (entry.isIntersecting) {
          observer.unobserve(entry.target);
          entry.target.backgroundColor = entry.target.color;
        }
      });
    };
/* 이 모든 과정에서 Observer가 관찰할 Target Element를 지정한다 */
  document.querySelectorAll(".imageCard").forEach((img) => {
    observer.observe(img);
  });

0개의 댓글