From c7752c1cee9e17e1e31ee689dea3564dbf97fd6e Mon Sep 17 00:00:00 2001 From: sryung Date: Sun, 24 Dec 2023 17:03:20 +0900 Subject: [PATCH] =?UTF-8?q?[=F0=9F=92=8E=20:=20refactor]=20userTimeline=20?= =?UTF-8?q?onSnap=20=EC=A0=9C=ED=95=9C=20=EA=B1=B8=EA=B8=B0=20(#12)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 유사한 작업을 timeline때 적용한 적 있으니 참고 (d37a720) - onSnapshot이 실시간으로 firestore의 정보를 read해와 사용량을 분당 1천회 사용하는 과금의 주원인이 됨 - onSnapshot과 fetchTweets 과정을 useEffect 내부로 이동시켜 cleanup 기능에 의존하는 방식 --- src/components/timeline.tsx | 2 +- src/components/user-timeline.tsx | 54 ++++++++++++++++++-------------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/components/timeline.tsx b/src/components/timeline.tsx index dbe337e..d0d290d 100644 --- a/src/components/timeline.tsx +++ b/src/components/timeline.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from 'react'; +import { Unsubscribe } from 'firebase/auth'; import { collection, limit, @@ -6,7 +7,6 @@ import { orderBy, query, } from 'firebase/firestore'; -import { Unsubscribe } from 'firebase/auth'; import { db } from '../firebase.ts'; import Tweet from './tweet.tsx'; import * as S from '../styles/timeline.ts'; diff --git a/src/components/user-timeline.tsx b/src/components/user-timeline.tsx index 7867a17..7fd25be 100644 --- a/src/components/user-timeline.tsx +++ b/src/components/user-timeline.tsx @@ -1,8 +1,9 @@ import { useEffect, useState } from 'react'; +import { Unsubscribe } from 'firebase/auth'; import { collection, - getDocs, limit, + onSnapshot, orderBy, query, where, @@ -15,30 +16,37 @@ import ITweet from '../interfaces/ITweet.ts'; export default function UserTimeline() { const user = auth.currentUser; const [tweets, setTweets] = useState([]); - const fetchTweets = async () => { - const tweetsQuery = query( - collection(db, 'tweets'), - where('userId', '==', user?.uid), - orderBy('createdAt', 'desc'), - limit(25), - ); - const snapshot = await getDocs(tweetsQuery); - const tweetList = snapshot.docs.map((doc) => { - const { userId, userName, tweet, createdAt, photo } = doc.data(); - return { - userId, - userName, - tweet, - createdAt, - photo, - id: doc.id, - }; - }); - setTweets(tweetList); - }; useEffect(() => { + let unsubscribe: Unsubscribe | null = null; + const fetchTweets = async () => { + const tweetsQuery = query( + collection(db, 'tweets'), + where('userId', '==', user?.uid), + orderBy('createdAt', 'desc'), + limit(25), + ); + unsubscribe = await onSnapshot(tweetsQuery, (snapshot) => { + const tweetList = snapshot.docs.map((doc) => { + const { userId, userName, tweet, createdAt, photo } = doc.data(); + return { + userId, + userName, + tweet, + createdAt, + photo, + id: doc.id, + }; + }); + setTweets(tweetList); + }); + }; fetchTweets(); - }, [tweets]); + return () => { + if (unsubscribe) { + unsubscribe(); + } + }; + }, []); return ( {tweets.map((tweet) => (