@@ -6,7 +6,15 @@ import React, {
66 useCallback ,
77 useContext
88} from 'react'
9- import { collection , getDocs , doc , updateDoc , addDoc } from 'firebase/firestore'
9+ import {
10+ collection ,
11+ getDocs ,
12+ doc ,
13+ updateDoc ,
14+ addDoc ,
15+ query ,
16+ where
17+ } from 'firebase/firestore'
1018import { ref , uploadBytes , getDownloadURL } from 'firebase/storage'
1119
1220import { db , storage } from '@/app/services/initializeFirebase.js'
@@ -31,36 +39,38 @@ export const DataProvider = ({ children }) => {
3139
3240 const { userProfile } = useAuth ( )
3341
42+ // Optmized fetchMatches version
3443 const fetchMatches = useCallback ( async ( ) => {
35- if ( userProfile && userProfile . collections ) {
36- setLoading ( true )
37- setError ( null )
38- const allMatches = [ ]
44+ if ( ! userProfile ?. collections ?. length ) return
3945
40- try {
41- for ( const col of userProfile . collections ) {
42- const colRef = collection ( db , col )
43- const querySnapshot = await getDocs ( colRef )
44-
45- querySnapshot . docs . forEach ( ( doc ) => {
46- const matchData = doc . data ( )
47- // Only add matches that are not marked as deleted
48- if ( ! matchData . _deleted ) {
49- allMatches . push ( {
50- id : doc . id ,
51- collection : col , // Track which collection this match belongs to
52- ...matchData
53- } )
54- }
55- } )
56- }
46+ setLoading ( true )
47+ setError ( null )
5748
58- setMatches ( allMatches )
59- } catch ( err ) {
60- setError ( err )
61- } finally {
62- setLoading ( false )
63- }
49+ try {
50+ // Create all promises at once instead of awaiting each one sequentially
51+ const collectionPromises = userProfile . collections . map ( async ( col ) => {
52+ const colRef = collection ( db , col )
53+ const filteredQuery = query ( colRef , where ( '_deleted' , '==' , false ) )
54+ const querySnapshot = await getDocs ( filteredQuery )
55+
56+ // Process documents in bulk rather than in forEach
57+ return querySnapshot . docs . map ( ( doc ) => ( {
58+ id : doc . id ,
59+ collection : col ,
60+ ...doc . data ( )
61+ } ) )
62+ } )
63+
64+ // Wait for all promises to resolve
65+ const matchesArrays = await Promise . all ( collectionPromises )
66+
67+ // Flatten the array of arrays
68+ setMatches ( matchesArrays . flat ( ) )
69+ } catch ( err ) {
70+ console . error ( 'Error fetching matches:' , err )
71+ setError ( err )
72+ } finally {
73+ setLoading ( false )
6474 }
6575 } , [ userProfile ] )
6676
@@ -110,6 +120,7 @@ export const DataProvider = ({ children }) => {
110120 }
111121 console . log ( pdfUrl )
112122 newMatchData . pdfFile = pdfUrl
123+ newMatchData . _deleted = false
113124
114125 const newMatch = {
115126 id : 'temp-id' ,
0 commit comments