10

In react-native-firebase v6, I can't get setBackgroundMessageHandler to work in my app. Notifications are received just fine but the handler is not executed.

I have done it like in the guide to no avail.

import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-community/async-storage';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

messaging().setBackgroundMessageHandler(async ({ data: { title, message } }) => {
    console.log('in background');
    // Save the notification locally
    const notificationList = JSON.parse(await AsyncStorage.getItem('@SM_NOTIFICATIONS')) || [];
    notificationList.push({ title, message, isRead: false });
    await AsyncStorage.setItem('@SM_NOTIFICATIONS', JSON.stringify(notificationList));
});

Nothing happened beside the incoming notifications. I expected the code to save the incoming notifications in AsyncStorage.

Dorklord
  • 416
  • 2
  • 6
  • 17

1 Answers1

12

Okay. After consulting the developer's team, I finally figure this one out.

First, setBackgroundMessageHandler must be called before registerComponent.

Second, don't send notification data. Only send custom data (silent push). Hence, you need to use local notification instead of push notification to display the notification in system tray.

Because Firebase Console somehow doesn't support silent push, I used FCM API v1 to send data-only. Here is my example:

POST https://fcm.googleapis.com/v1/projects/my-project/messages:send

{
    "validate_only": false,
    "message": {
        "name": "XXX",
        "data": {
            "title": "BG 2",
            "message": "BG BARU"
        },
        "topic": "C3166"
    }
}

As you can see, no notification field in JSON above.

Dorklord
  • 416
  • 2
  • 6
  • 17
  • "First, setBackgroundMessageHandler must be called before registerComponent" where did you get that? why it's not documented? – Tuan Dat Tran Jan 14 '21 at 15:46
  • @TuanDatTran tbh I already forget why. I think I get it from trial and error. – Dorklord Jan 15 '21 at 07:07
  • 3
    It is documented, check it out [here](https://rnfirebase.io/messaging/usage#background--quit-state-messages). _To setup a background handler, call the setBackgroundMessageHandler outside of your application logic as early as possible._ – adamvx Jan 16 '21 at 18:19
  • setBackgroundMessageHandler is working in iOS for you. Its not triggered in my app when App is closed. – Nauman Asghar Jan 20 '21 at 11:23
  • So how would you get notifications when app is closed? – Timur Ridjanovic Jul 26 '21 at 20:40
  • SOLUTION - I was struggling with this for some time. Removing the notification from the payload solved the problem! Thank you Dorklord – Chris GW Green Mar 29 '22 at 16:20