Skip to content

Commit 5ed57c4

Browse files
committed
refactor: replace Firestore data fetching with real-time updates using onSnapshot
1 parent cf7b39b commit 5ed57c4

File tree

1 file changed

+28
-21
lines changed

1 file changed

+28
-21
lines changed

components/Authors/Authors.tsx

+28-21
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1-
import { collection, getDocs } from "firebase/firestore";
1+
"use client";
2+
3+
import { collection, onSnapshot } from "firebase/firestore";
24
import { db } from "@/lib/firebase";
35
import Image from "next/image";
46
import Link from "next/link";
7+
import { useEffect, useState } from "react";
58

69
// Define the structure of an author
710
type AuthorType = {
@@ -14,20 +17,6 @@ type AuthorType = {
1417
city: string;
1518
};
1619

17-
// Function to fetch authors from Firestore
18-
const getAuthors = async (): Promise<AuthorType[]> => {
19-
const authorsCollection = collection(db, "authors");
20-
const authorsSnapshot = await getDocs(authorsCollection);
21-
22-
return authorsSnapshot.docs.map((doc) => {
23-
const data = doc.data() as AuthorType;
24-
return {
25-
...data,
26-
id: doc.id,
27-
};
28-
});
29-
};
30-
3120
// Function to shuffle an array
3221
const shuffleArray = (array: any[]) => {
3322
for (let i = array.length - 1; i > 0; i--) {
@@ -37,16 +26,34 @@ const shuffleArray = (array: any[]) => {
3726
return array;
3827
};
3928

40-
export default async function Authors() {
41-
const data: AuthorType[] = await getAuthors();
29+
export default function Authors() {
30+
const [authors, setAuthors] = useState<AuthorType[]>([]);
31+
32+
useEffect(() => {
33+
const authorsCollection = collection(db, "authors");
34+
35+
// Set up the listener
36+
const unsubscribe = onSnapshot(authorsCollection, (snapshot) => {
37+
const data: AuthorType[] = snapshot.docs.map((doc) => {
38+
const authorData = doc.data() as AuthorType;
39+
return {
40+
...authorData,
41+
id: doc.id,
42+
};
43+
});
44+
45+
// Shuffle the authors and select the first 4
46+
const shuffledAuthors = shuffleArray(data);
47+
setAuthors(shuffledAuthors.slice(0, 4));
48+
});
4249

43-
// Shuffle the authors and select the first 4
44-
const shuffledAuthors = shuffleArray(data);
45-
const selectedAuthors = shuffledAuthors.slice(0, 4);
50+
// Cleanup the listener on unmount
51+
return () => unsubscribe();
52+
}, []);
4653

4754
return (
4855
<div className="grid grid-cols-1 lg:grid-cols-2 mb-48 max-w-[95rem] w-full mx-auto">
49-
{selectedAuthors.map((author) => (
56+
{authors.map((author) => (
5057
<article
5158
className="flex flex-col sm:flex-row sm:items-center gap-4 sm:gap-8 md:gap-12 p-4 md:p-8 border border-white"
5259
key={author.id}

0 commit comments

Comments
 (0)