20210708 TIL

Breadman·2021년 7월 8일
0

항해99

목록 보기
25/28
post-thumbnail

무한 스크롤

지난 주 TIL에서 무한 스크롤을 구현하고 정리했었다.
이번 과제에도 무한 스크롤이 있어서, 강의에서 나온 방법말고 이전에 구현했던 방법으로 시도했었지만 잘 동작하지 않았다.
이전에 구현했던 방법은 event.target.scrollTop, clientHeight, scrollHeight 을 연산하는 것이었다. 이번엔 왠지 event.target의 scrollTop, clientHeight, scrollHeight 모두 undefined가 나왔다.
알고보니 scroll Event가 발생하는 target이 document 였고, 해당 값을 가져오려면 event.target.documentElement 에서 가져와야했다.

강의에서 구현한 방법은,
scrollTop = document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop,
scrollHeight = document.body.scrollHeight,
innerHeight = window.innerHeight

를 연산하는 것이었다.

결과적으로는 이전에 구현했던 값들과 동일했고, 조금만 신중하게 봤더라면 이전 방법으로 구현할 수 있었던 기능이었다.

firestore paging

무한스크롤을 구현하기 위해선, 데이터를 페이징 단위로 불러올 필요가 있다. 즉 한번에 불러올 컨텐츠의 개수를 정해야하고, 그 개수만큼만 불러와야한다.
firestore에서는 query를 이용해 시작점, 끝점, 개수를 정할 수 있다.

const postDB = firebase.firestore().collection('post');

const query = postDB.orderBy('createdAt', 'desc');
query = query.startAt(doc);	// doc으로 시작점 지정.
query = query.limit(3); 	// 정렬된 docs에서 3개만 가져오기로 지정.

강의에서 구현한 무한 스크롤의 경우, 다음 준비물이 필요하다.

  • start: 시작점. (default: null)
  • next: 다음 지점을 미리 저장. (default: null)

구현 설명은 아래와 같다.

let start = null;
let next = null;
const size = 3;

const handleScroll = () => {
  if(!스크롤이 바닥까지 도착) {
    return;  
  }
  
  if(start && !next) {
    return;
  }
  
  let query = postDB.orderBy('createAt', 'desc');
  if(start) {
    query = query.startAt(start).limit(size + 1);
    // 일부러 사이즈보다 하나 더 불러옴.
    // 이번에 3개 불러왔을 때, 다음 번에도 불러올 데이터가 있는지 확인용.
  }
  query.get()
    .then((docs) => {
      ...
      start = docs.docs[0];
      next = docs.docs.length === size + 1
              ? docs.docs[size]
              : null,
        // 사이즈+1개 만큼 못 불러왔으면 null을 넣어줌.
        // 그럼 위의 if(start && !next) 를 타고 중단.
    })
}
profile
빵돌입니다. 빵 좋아합니다.

0개의 댓글