You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用读取Firestore数据报错:Cannot read property 'forEach' of undefined问题排查与解决咨询

Fixing "Cannot read property 'forEach' of undefined" in Firestore Data Fetch

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, so Users or user would 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 the forEach loop to handle that scenario gracefully.

内容的提问来源于stack exchange,提问作者Gratis Devs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:17:26