How to get data from notification, without clicking on notifications (firebase cloud messagin and react native)

Viewed 446

Right now I can handle messages when the app is open, minimized, or closed, but when I click on the notification. How to process a message if a user logs into the application without notification?

 useEffect(() => {
    messaging().setBackgroundMessageHandler(async remoteMessage => {
        handlerMessage(remoteMessage)
        setInitialRoute('Messenger')
    });
    messaging().onMessage(async remoteMessage => {
        handlerMessage(remoteMessage);
    });

    messaging()
        .getInitialNotification()
        .then(remoteMessage => {
            if (remoteMessage) {
                handlerMessage(remoteMessage);
                setInitialRoute('Messenger')
            }
        });
}, []);
1 Answers

first of all, your "setBackgroundMessageHandler" should be located in your index.js like mentioned in the react-native-firebase docs. You should take another look at that. Now to your question: You want to process data from a fcmNotification that was sent while your app is in background or quit state. Your setBackgroundMessageHandler is not allowed to update any UI (e.g. via state , like mentioned in the docs). However it can perform network requests or update the localStorage. And this is what you should be doing. When a message arrives trough the backgroundHandler, update your LocalStorage. On the next start of your app, you can check if the LocalStorage contains data from a message the backgroundHander processed. If yes, do something with it and delete it after so the next App start wont trigger an action with the old data. If no, -well- do nothing.

Related