Question:
Preventing firestore onUpdate cloud functions while using onSnapshot in JS

Problem

I got a question about onSnapshot and cloud functions behavior.


If I use onSnapshot, as far as I understand, it does most locally and then updates with the cloud every 1 sec with a hook. But I have a cloud function functions.firestore.document(...).onUpdate and this one will be called every time of those update hooks if I have like a text field. The function itself is there to check if a type field (typeA,typeB) has been changed, and if so it does some stuff in other collections.


Can I trigger the function somehow manually, like when the subscription is unsubscribed, for example, that would be the best. but then I can't compare using the snap.before/after functionality in the cloud functions?


What would be a good way to handle this?


Here is my cloud function, it updates the parent document if the type field is changed in the updated document. And I don't want to have tons of invocations on OnSnapshot updates


export const incrementCountsOnUpdate = functions.firestore

  .document('parent/{parentId}/chiild/{chiildId}')

  .onUpdate(async (snap, context) => {

    const beforeType = snap.before.data().type

    const afterType = snap.after.data().type

    if (beforeType === afterType) return

    const setRef = snap.before.ref.parent.parent

    if (setRef) {

      await setRef.update({

        [getCounter(beforeType)]: FieldValue.increment(-1),

        [getCounter(afterType)]: FieldValue.increment(1)

      })

    }

  })


Solution

Can I trigger the function somehow manually, like when the subscription is unsubscribed for example, that would be the best?


No, you can't trigger it manually.


What would be a good way to handle this?


You can write another HTTP-type function and invoke it from your app whenever you want.


Suggested blogs:

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers