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) => (