Search code examples
javascriptfirebasevue.jsgoogle-cloud-firestorepinia

Adding lists to firebase with VUEJS 3


I have a list of items 'order' which I want to add to my cloud firestore.

order: [
        {
     
          product: 'Tea',
          productivity: '15',
          quantity: '10',
        },
        {
          
          product: 'fruits',
          productivity: '15',
          quantity: '11',
        },
      ],

before my app was simple where I could add only one product and this function was working fine (this formula comes from pinia store)

    async addOrder(clientsid, newOrderProduct, newOrderProductivity, newOrderQuantity) {
      const storeAuth = useStoreAuth()

      await addDoc(collection(db, 'users', storeAuth.user.id, 'clients', clientsid, 'orders'), {
        
        product: newOrderProduct,
        productivity: newOrderProductivity,
        quantity: newOrderQuantity,
        productionTime: newOrderQuantity / newOrderProductivity
   
            
      })
  
    },

but now I want to add multiple products at the same time. Currently I am adding data locally. Basically it is simple cart but I couldn't find something which would suit my case.

This is code where I call function addOrder in my component.

  const addOrders = () => {

    storeOrders.addOrder(newOrderName.value, newOrderProduct.value, newOrderProductivity.value, newOrderQuantity.value)
    
    newOrderProduct.value
    newOrderProductivity.value = ''
    newOrderQuantity.value = ''



  }

Solution

  • If it works for you, you can adapt it to your code, when adding several products at the same time you have to create a map and convert it asynchronously, in this way the article would have its own unique identification

    const order =  [
      {
    
        product: 'Tea',
        productivity: '15',
        quantity: '10',
      },
      {
        
        product: 'fruits',
        productivity: '15',
        quantity: '11',
      },
    ];
    
    order.map(async(item)=> {
      await addDoc(collection(db, 'users', storeAuth.user.id, 'clients', clientsid, 'orders'), {
        product: item.product,
        productivity: item.productivity,
        quantity: item.quantity,
        productionTime: item.quantity / item.productivity
      })
    })