Renato Krcelic
Renato Krcelic

Reputation: 649

How to listen to a specific value change in Firebase?

My data structure is the following: compliments/received/{uid}/{complimentId} enter image description here

I would like to listen to changes on compliments/received/{uid}/{complimentId}/updatedAt

My code is:

firebase.database().ref('compliments/received/' + currentUser._id).on('child_changed', (snap) => {
  console.log('update in action', snap.val())
  snap.ref.child('updatedAt').on('value', () => onUpdate(snap))
});

The problem: This listener triggers when I update any field on the given database path, eg: when I set "seen" from 0 to 1. I would like to trigger this listener only when the updatedAt field's value changes.

What I tried so far:

firebase.database().ref('compliments/received/' + currentUser._id).on('child_changed', (snap) => {
  console.log('update in action', snap.val())
  snap.ref.child('updatedAt').on('child_changed', () => onUpdate(snap))
});

This listener does not trigger when I change the updatedAt field's value.

Any recommendations are welcome! Thanks!

Solution as per Ali's answer:

firebase.database().ref('compliments/received/' + currentUser._id).on('child_added', (snap) => {
    console.log('add in action', snap.val());
    firebase.database().ref('compliments/received/' + currentUser._id)
    .child(snap.key).child('updatedAt').on('value', async () => {
      const newSnap = await firebase.database().ref('compliments/received/' + currentUser._id)
      .child(snap.key).once('value')
      onUpdate(newSnap)
    })
});

Upvotes: 5

Views: 4491

Answers (2)

AleeGomes
AleeGomes

Reputation: 1

const { getDatabase, ref, onChildAdded } = require('firebase/database');

    const db = getDatabase();
    
    onChildAdded(ref(db, 'compliments/received/' + currentUser._id), (snapshot) => {
        
        console.log(snapshot.val())
        
    })

Upvotes: 0

Ali Faris
Ali Faris

Reputation: 18592

checkout this

firebase.database().ref('compliments/received/' + currentUser._id).on('child_added', (snap) =>
{
    console.log('add in action', snap.val());
    firebase.database().ref('compliments/received/' + currentUser._id)
    .child(snap.key).child('updatedAt').on('value', (updateSnap) => onUpdate(updateSnap))
});

Upvotes: 3

Related Questions