firebase data 시간순서대로 정렬하기

OwlSuri·2022년 4월 16일
2

11부터 22, 33, ... ,00 까지 입력한 fireBase의 데이터를 가져오면

이렇게 원하는 대로 나오지 않는다.

이유는 firebase에 데이터를 입력할때 파이어베이스가 임의의 id값을 주고 그것으로 정렬을 하는 것이 디폴트이기 때문이다.

시간의 순서대로 정렬하고 싶어서 찾아보니
.orderBy("timestamp", "desc")
로 가능 하다는 구글링의 결과에 따라 여기저기 넣어봤지만, 결과는

파이어베이스의 값을 가져올때 query를 사용하는 방법과 getDocs를 사용하는 방법이 있는데, .orderBy("timestamp", "desc") 이것을 함수처럼 사용하는 것은 query로 가져올때 가능한 방법이었다.

우리는 getDocs를 사용했기 때문에 방법이 조금 달랐다.

firebase data 시간순으로 정렬하는 방법

  1. timestamp를 new Date() 함수를 이용해 입력하기
await addDoc(board, {
          writer,
          title,
          contents,
          timestamp: new Date()
        },
      );

Number(new Date())로 넣어도 무방하다.

  1. 데이터를 불러오는 부분에 orderBy와 query를 import하고, getDocs부분에 query를 호출하는 방식으로 orderBy를 넣기

import { collection, getDocs, getFirestore, orderBy, query } from "firebase/firestore/lite"

  useEffect (() => {
    async function fetchBoards() {
      const board = collection(getFirestore(firebaseApp),"board")
      const result = await getDocs(query(board, orderBy("timestamp", "desc")));
      const boards = result.docs.map((el) => el.data());
      setFireData(boards);
    }
    fetchBoards();
  }, []);

이렇게하면 시간의 내림차순으로 정렬된 데이터를 볼 수 있다.




profile
기억이 안되면, 기록을 -

0개의 댓글