When calling the data() method inside a Firestore 9 onSnapshot function it returns an Object containing all fields in the document.
But in my code below there is a TypeScript error on ...doc.data() that says: Spread types may only be created from object types. ts(2698)
So if data() returns an object, why is TypeScript complaining that it is not an object?
const unsubscribe = onSnapshot(
collectionOrdered,
(snapshot) => {
snapshot.docs.forEach((doc) => {
documents.push({ ...doc.data(), id: doc.id });
});
error.value = null;
console.log(documents);
},
(err) => {
console.log(err.message);
documents.splice(0);
error.value = err.message;
}
);
I had trouble finding it, but it looks like the doc inside snapshot needed to by typed as doc: DocumentData.
Full code example:
const unsubscribe = onSnapshot(
collectionOrdered,
(snapshot) => {
snapshot.docs.forEach((doc: DocumentData) => {
documents.push({ ...doc.data(), id: doc.id });
});
error.value = null;
console.log(documents);
},
(err) => {
console.log(err.message);
documents.splice(0); //Clears reactive array
error.value = err.message;
}
);