firebase 6 실시간 업데이트

김부릉·2023년 3월 16일
0

onSnapshot()를 사용하여 실시간 업데이트를 한다.

import { collection, onSnapshot, orderBy,} from "firebase/firestore";

const [nweets, setNweets] = useState([]);

useEffect(() => {
    const q = query(
      collection(dbService, "nweets"),
      orderBy("createdAt", "desc")
    );
   
    onSnapshot(q, (snapshot) => {
      const nweetArr = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      setNweets(nweetArr);
    });
  }, []);

  • 컬렉션 nweets를 생성 날짜 순으로 가져오기 위해 query() 사용
  • onSnapshot() 으로 배열 생성 뒤에 setNweets()에 담는다

0개의 댓글