javascriptreactjsfirebasegoogle-cloud-firestore

Firestore React Js Increment Value by FieldValue without Google Cloud Function


Is there a way to increment integer by FieldValue without having to deal with HTTP, Google Cloud Function?

And if there is, may I ask how? Because I kept getting error from this "firestore is not defined, firebase is not defined, admin is not defined, FieldValue is not defined" even though I tried to import to the project already.

import { db } from "../utils/firebase.js"

import {
  collection,
  doc,
  setDoc,
  getDocs,
  getDoc,
  deleteDoc,
  onSnapshot,
  updateDoc,
  query,
  limit,
  where,
  increment,
  FieldValue,
} from "firebase/firestore"
 
export async function increaseStock(data) {
  const queryCompanyProduct = query(collection(db, "order"))
    await updateDoc(doc(db, "order", data.id), {
    grandtotal: FieldValue.increment(50), 
    // I tried firebase.firestore.FieldValue.increment(50) = also error..    
  })
}

Solution

  • Follow the example in the documentation. There is no need to import or use FieldValue directly when using the newer modular API.

    import { query, collection, doc, updateDoc, increment } from "firebase/firestore";
    
    const queryCompanyProduct = query(collection(db, "order"))
    await updateDoc(doc(db, "order", data.id), {
      grandtotal: increment(50), 
    })