Tính năng cập nhật tức thời - Không cần refresh
Xây dựng bảng tin thảo luận real-time như Slack/Discord cho cộng đồng của bạn.
Use case congdongvibecode: Khi ai đó đăng bài mới trong Community Feed, tất cả thành viên đang online sẽ thấy bài viết xuất hiện ngay lập tức mà KHÔNG CẦN F5.
Prompt cho Gemini (React/Next.js): "Viết React hook useRealtimePosts() sử dụng Firestore onSnapshot để:
- Lắng nghe collection posts theo communityId
- Sắp xếp theo createdAt giảm dần
- Giới hạn 50 bài mới nhất
- Cleanup listener khi component unmount"
Code được generate:
import { useEffect, useState } from 'react';
import { collection, query, where, orderBy, limit, onSnapshot } from 'firebase/firestore';
import { db } from '@/lib/firebase';
export function useRealtimePosts(communityId: string) {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const q = query(
collection(db, 'posts'),
where('communityId', '==', communityId),
orderBy('createdAt', 'desc'),
limit(50)
);
const unsubscribe = onSnapshot(q, (snapshot) => {
const newPosts = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
setPosts(newPosts);
setLoading(false);
});
return () => unsubscribe(); // Cleanup
}, [communityId]);
return { posts, loading };
}
Demo trực quan:
- Mở 2 tab browser cùng trang Community
- Đăng bài từ tab 1
- Tab 2 tự động hiển thị bài mới - MAGIC! 🪄
