Home > database >  Setting up a counter in a document and then retrieve it using Firestore: Would this be alright or wo
Setting up a counter in a document and then retrieve it using Firestore: Would this be alright or wo

Time:03-23

Under the orders collection, I created a document called counts which would store the counts for the status of the orders:

enter image description here

I then created a function to increment the status with "delivered"

      async function updateData() {
 
      const docRef = doc(db, "orders", "count");
      await updateDoc(docRef, {
        [`deliveredOrders`]: increment(1),
      });

  }

And then to display this:

 useEffect(async () => {
    const docRef = doc(db, "orders", "counts");
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
      console.log("Document data:", docSnap.data());
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
  }, []);

CodePudding user response:

Yes, this is one way to do it I suppose, 'expensive', that's up to you and how many calls you might end up with, as I know Firestore has a limited amount of free document calls.

Another thing is you should not, and I repeat should not make a useEffect asynchronous, the best and right way to perform asynchronous code inside a useEffect would be to declare it inside and then run it like below

useEffect(() => { 
    const AsyncExample = async () => { 
      // async code in here 
    }
    AsyncExample() 
}, [])
  • Related