Cloud function firebase add to cart reactjs?

Viewed 354

I am trying to create a shopping cart and save it to firebase using redux-saga. my carts like this

{
  products: [
    {
      product_id: 'id1',
      product_name: 'product 1',
      product_quantity: 2,
      product_price: 50,
    },
    {
      product_id: 'id2',
      product_name: 'product 2',
      product_quantity: 2,
      product_price: 2,
    }
  ],
  userID: 'user1'
}

firebase.js

export const addToCartFirebase = (cart) => {
  firestore.send(cart); //fake
};

cart.saga.js

export function* handleAddToCart(action) {
  const { cart } = action;
  const newCart = yield call(addToCartFirebase, cart);
}

I am very new to firebase. How I make cloud functions receive a cart and if it exists in the database it just increases the quantity of product, if the cart does not exist in the database it creates a new one

1 Answers

You don't really need to use a cloud function for this (you could though if that's important). You could simply fetch the existing user document and update the products array accordingly. Something like this:

const addCart = async product {
  const db = firestore().collection(userCollection);
  const userSnap = await db.where("userID", "==", "user1").get();
  const userDoc = userSnap.docs[0].exists ? { id: userSnap.docs[0].id, ...userSnap.docs[0].data() } : null;
  if (userDoc) { // If user exists, update his products array
    const products = userDoc.products.some(prod => prod.product_id === product.product_id)
      ? userDoc.products.map(prod => prod.product_id === product.product_id ? ({ ...prod, product_quantity: prod.product_quantity + 1 }) : prod)
      :
      [ ...userDoc.products, product ];
      await db.doc(userDoc.id).update({ products });
  }
  else {
     const newUserData = { userID: "user1", products: [product] };
     await db.add(newUserData);
  }
}
Related