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);
}
- [Vuejs]-Vue 3 custom component render as string and passed to other component as prop
- [Vuejs]-Create virtual host for vuejs app return Invalid Host header by nginx
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);
}
- [Vuejs]-"Failed to mount component: template or render function not defined" in Vue, despite using full compiler bundle
- [Vuejs]-Mix Dynamic class with data binders in Vue.js
Source:stackexchange.com