1
- import { collection , getDocs } from "firebase/firestore" ;
1
+ "use client" ;
2
+
3
+ import { collection , onSnapshot } from "firebase/firestore" ;
2
4
import { db } from "@/lib/firebase" ;
3
5
import Image from "next/image" ;
4
6
import Link from "next/link" ;
7
+ import { useEffect , useState } from "react" ;
5
8
6
9
// Define the structure of an author
7
10
type AuthorType = {
@@ -14,20 +17,6 @@ type AuthorType = {
14
17
city : string ;
15
18
} ;
16
19
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
-
31
20
// Function to shuffle an array
32
21
const shuffleArray = ( array : any [ ] ) => {
33
22
for ( let i = array . length - 1 ; i > 0 ; i -- ) {
@@ -37,16 +26,34 @@ const shuffleArray = (array: any[]) => {
37
26
return array ;
38
27
} ;
39
28
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
+ } ) ;
42
49
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
+ } , [ ] ) ;
46
53
47
54
return (
48
55
< 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 ) => (
50
57
< article
51
58
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"
52
59
key = { author . id }
0 commit comments