YanivCode
YanivCode

Reputation: 144

firestore update value in array inside doc

I'm looking at the firestore docs for hours and still didnt found solution for this case. I need to add an ammout feature to product my E-commerce app.

data structure : the main collection is "cart" and the doc is the user email.

here is the current code for add or set a product:

import firebase from 'firebase';


export async function addToCart(userMail, itemId, name, url, price, category, type, description) {
    const ammout = 1
    const cartItem = { itemId, name, url, price, category, type, description, ammout }
    if (userMail === undefined) throw console.error('please Login');

    const userDoc = await firebase.firestore().collection("cart").doc(userMail)

    await userDoc.get().then((doc) => {
        if (doc.exists) {
            (async () => {
                    

                await userDoc.update({
                    item: firebase.firestore.FieldValue.arrayUnion(cartItem),
                })
            })()
        }
        else {
            (async () => {
                await userDoc.set({
                    item: firebase.firestore.FieldValue.arrayUnion(cartItem)
                })
            })()
        }

    })
}

Upvotes: 2

Views: 51

Answers (1)

Rafael Lemos
Rafael Lemos

Reputation: 5829

The issue could be that you are using both await and Promise.then() in the same function, this could be creating some synchonicity issue, also you don't need to await for the userDoc variable to be populated, as you can see on the firestore documentation example.

So basically I would remove all the async/await from your code as they are not really needed and the Promise.then() on the .get() will be enough to ensure synchronicity in your code which could look something like this:

export function addToCart(userMail, itemId, name, url, price, category, type, description) {
    const ammout = 1
    const cartItem = { itemId, name, url, price, category, type, description, ammout }
    if (userMail === undefined) throw console.error('please Login');

    const userDoc = firebase.firestore().collection("cart").doc(userMail)

    userDoc.get().then((doc) => {
        if (doc.exists) {
            userDoc.update({
                item: firebase.firestore.FieldValue.arrayUnion(cartItem),
            })
        }
        else {
            userDoc.set({
                item: firebase.firestore.FieldValue.arrayUnion(cartItem)
            })
        }

    })
}

Upvotes: 1

Related Questions