[Vuejs]-Issue with setDoc() and updateDoc() when using "if" "else"

1👍

The error

Error adding product to cart: TypeError: Cannot read properties of
undefined (reading ‘quantity’)

indicates that the field quantity is undefined in the productDoc.

So either you enforce through security rules that quantity has a correct value when the productDoc doc is created/updated or you adapt your code to handle this case as follows, for example:

const productRef = doc(db, "carts", cartId, "cartProducts", this.productName);
const productDoc = await getDoc(productRef);
console.log(JSON.stringify(productDoc.data()));
if (productDoc.exists && productDoc.data().quantity) {
    await updateDoc(productRef, {
        quantity: productDoc.data().quantity + 1
    });

} else {
    await setDoc(productRef, product);
}

0👍

solved using runTransaction

import { runTransaction } from "firebase/firestore";
const productRef = doc(db, "carts", cartId, "cartProducts", this.productName);

                    try {
                        await runTransaction(db, async (transaction) => {
                            const newQ = await transaction.get(productRef);
                            if (!newQ.exists()) {
                                await setDoc(productRef, product);
                                throw " Document no exist ";
                            }
                            const newQuant = newQ.data().quantity + 1;
                            transaction.update(productRef, { quantity: newQuant });

                        });
                        console.log("Transaction successfully committed!");
                    } catch (e) {
                        console.log("Transaction failed: ", e);
                    }

Leave a comment