Home > OS >  Type 'Promise<QuerySnapshot<DocumentData>>' must have a '[Symbol.iterator
Type 'Promise<QuerySnapshot<DocumentData>>' must have a '[Symbol.iterator

Time:10-26

I am working on a Firebase project using NextJS and Typescript. I am trying to fetch data from Firestore database and I am getting this error Type 'Promise<QuerySnapshot<DocumentData>>' must have a '[Symbol.iterator]()' method that returns an iterator.

Here is the code that I am using to fetch data from the db

const postsRef = collection(db, "discussions");
query(postsRef, orderBy("createdAt"), limit(20));
const [posts]  =  getDocs(postsRef)

CodePudding user response:

Your getDocs doesn't return an array which is why you get this error. A QuerySnapshot is a custom Firebase type which has forEach (similar to an array), but is not an array. So you need to iterate through it using the forEach:

const postsRef = collection(db, "discussions");
query(postsRef, orderBy("createdAt"), limit(20));
// I'm guessing you need await here too?
const postDocs  =  await getDocs(postsRef)

let posts = []
postDocs.forEach((postDoc) => {
  posts = [...posts, {
    ...postDoc.data(),
    id: postDoc.id,
  }]
})
  • Related