React应用读取Firestore数据报错:Cannot read property 'forEach' of undefined问题排查与解决咨询
Hey there, let's get your Firestore data fetch working smoothly! That error you're hitting comes from a straightforward typo in your code—here's the full breakdown:
The Root Cause
When you run await response.get(), Firestore returns a QuerySnapshot object. This object stores the retrieved document list in the docs property (plural form), not doc (singular). Accessing data.doc gives you undefined, which is why calling forEach on it throws that error.
Corrected Code
Here's the fixed version of your fetchUsers function, plus I added error handling to catch other potential issues down the line:
fetchUsers = async () => { try { const db = firebase.firestore(); const response = db.collection('users'); const data = await response.get(); // Use data.docs instead of data.doc data.docs.forEach(item => { console.log(item.data()); // Add .data() to access the document's actual content! }); } catch (error) { console.error('Error fetching users:', error); } }
A quick tip: I included item.data() in the console log—if you just log item, you'll get the QueryDocumentSnapshot object itself. Using .data() pulls out the actual data stored in the document, which is likely what you need.
Extra Checks to Confirm Stability
- Double-check your collection name is exactly
users(Firestore is case-sensitive, soUsersoruserwould break the fetch). - Your security rules are set to allow all reads/writes, so permissions aren't the issue here—great call sharing those!
- For empty collections, add a check like
if (data.empty) { console.log('No users found'); }before theforEachloop to handle that scenario gracefully.
内容的提问来源于stack exchange,提问作者Gratis Devs

