Faizan Butt
Faizan Butt

Reputation: 41

React Native Firebase push notification

I have a requirement to automatically send push notifications to my application when new data is inserted into firebase. Is there any way to do so ? Thanks !

Upvotes: 0

Views: 783

Answers (2)

rufatmammadli
rufatmammadli

Reputation: 78

You can use Firebase Functions as a middleware function for sending push notifications via FCM to the device If the database value is changed.

Adding an example from my FirebaseDBtoFCMFunction repo.

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

exports.sendPushNotification = functions.database
    .ref('/users/{user_id}') // Put your path here with the params.
    .onWrite(async (change, context) => {
        try {
            const { after } = change;
            const { _data } = after;
            const { deviceToken } = _data.receiver; // Always send the device token within the data entry.
            
            if(!deviceToken) return;
            
            const payload = {
                notification: {
                    title: 'Notification',
                    body: `FCM notification triggered!`
                },
                data: context.params // Passing the path params along with the notification to the device. [optional]
            };
            
            return await admin.messaging().sendToDevice(deviceToken, payload);
        } catch (ex) {
            return console.error('Error:', ex.toString());
        }
    });

Upvotes: 1

ozkulah
ozkulah

Reputation: 64

Inside your application add child_change (valueChanged) or child_add event for specific database location than when it changes, it will fired. From doc.

FirebaseDatabase.DefaultInstance
        .GetReference("Leaders").OrderByChild("score")
        .ValueChanged += HandleValueChanged;
    }

    void HandleValueChanged(object sender, ValueChangedEventArgs args) {
      if (args.DatabaseError != null) {
        Debug.LogError(args.DatabaseError.Message);
        return;
      }
      // Do something with the data in args.Snapshot
    }

For nodejs value listener

Upvotes: 0

Related Questions