Vik
Vik

Reputation: 9289

firebase realtime DB updating a specific value goes to infinite loop

my code is like below

updateUserCount(){
    console.log("started user update")
    this.db.object('/analytics').valueChanges().map(
      (snapshot) => {return snapshot}
    ).subscribe(
      (res:any) => {
                        console.log("Vik:::total users in the system are:" + res.userCount)
                        this.db.object('/analytics').update({"userCount": Number(res.userCount) + 1}).then(
                          (r) => console.log("count updated")
                        ).catch(
                          err => console.log("error updating count:" + err)
                        )
      })
  }

It simply trying to add one to property userCount. But the update statement puts this into infinite loop.

Upvotes: 1

Views: 696

Answers (1)

Karan Bhomia
Karan Bhomia

Reputation: 169

What is understand from the code above is that you want to update a "userCount", every time the collection is updated. Although I do not know the exact solution here, but may I suggest an alternative approach.

1) Add a cloud function (https://firebase.google.com/docs/functions/) which triggers every time a value is added to the collection.

2) The code would look something like this in TypeScript

import * as functions from 'firebase-functions';
import { DocumentSnapshot } from '../node_modules/firebase-functions/lib/providers/firestore';

export const valueAddFunction = functions.firestore.document('/analytics/{id}')
.onCreate((snap: DocumentSnapshot, context: any) => {
    const original = snap.data().original
    console.log("original " + original)
    return snap.ref.set({key: "WhateverValueYouWant"}, {})
})

This function would be triggered whenever a new document is added to the collection. You can similarly add functions listening to updates. Hope this helps.

Upvotes: 1

Related Questions