Home > OS >  How to get all documents in Firestore (v9) sub collection
How to get all documents in Firestore (v9) sub collection

Time:06-30

I'm trying to get all documents in all sub-collection with Firebase V9, so I used collectionGroup to retrieve the data.

Here is my Firestore architecture :

bots (collection)
    | id (doc ID)
        | order_history (sub collection)
            | id (doc ID)
                createdBy: uid (user uid)

enter image description here

And this is how I try to get documents :

const [orders, setOrders] = useState([]);
const { user } = useAuth();

const getOrders = async () => {
    const orders = await getDocs(query(collectionGroup(db, 'order_history'), where('createdBy', '==', user.uid)));
setOrders(orders.docs.map((doc) => ({
  ...doc.data()
})))
  }

useEffect(() => {
    getOrders();
    console.log('orders ', orders); // return []
}, []);

This code returns an empty array.

Did I do something wrong?

CodePudding user response:

Your getOrders anonymous method execution requires an explicit return statement if there's more than 1 statement. Implicit returns work when only a single statement exists (and after some testing, return await X doesn't appear to work either).

const getOrders = async () => {
    const orders = await getDocs(...);
    setOrders(orders.docs.map(...))
}

Needs to be


const getOrders = async () => {
    const orders = await getDocs(...);
    return setOrders(orders.docs.map(...))
}

CodePudding user response:

I think your getOrders function is asynchronus function. If you want debug log I think you should waiting for getOrders completed then orders had been updated.

Ex:

useEffect(() => {
    console.log('orders ', orders);
}, [orders]);
  • Related