Foreground & Background Push Notification Using Firebase, React Native & Expo
Firebase Cloud Messaging (FCM) & React Native. JavaScript Code
Hey..!! My name is Rohit. Well, I am not a professional content writer. But I will ensure that at the end of this article, you can add a Foreground and Background Push Notification Feature With Firebase to your react native & expo applications.
I recommend that you watch the step-by-step tutorial here:
Project setup, Package Requirements, and Code
Attention all developers seeking to make social connections and establish themselves while earning passive income — look no further! I highly recommend ‘From Code to Connections’, a book that will guide you through the process. Don’t miss out, grab your copy now on Amazon worldwide or Amazon India! You can also go for Gumroad
- npm package installation. I am following this official documentation.
npm install --save @react-native-firebase/app
npm install --save @react-native-firebase/messaging
- We need a few more packages. But for now, let’s settle with these two. Next, In App.js, copy and paste the required code from the official documented site.
const requestUserPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
}
- We will use the useEffect hook to remember the states of the push notification
useEffect(() => {
if (requestUserPermission){
// return fcm token for the device
messaging().getToken().then(token => {
console.log(token);
});
}
else {
console.log("Failed Token Status", authStatus);
}
}, [])
- Check whether an initial notification is available. Place the below code snippet inside the useEffect hook.
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
- Assume a message notification contains a “type” property in the data payload of the screen to open. Place the below code also inside the useEffect hook.
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
});
- Now, at last, register a background handler inside the useEffect hook.
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
- Call the onMessage method inside your application code to listen to messages in the foreground. Code executed via this handler has access to React context and can interact with your application (e.g. updating the state or UI).
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
return unsubscribe;
}, []);
- For now, we don’t need any extra code. Yeah, you can customize your application according to the requirements. But, This is the basic code of the Push Notification from the background and foreground state of the application Using Firebase cloud messaging, react native, and expo.
- Next, you must install the expo dev client package of the react native expo. Why? Because we just used the native code of the react-native. So, we can’t test our application in the expo go mobile application. If you are an expo user, then you can use either the Prebuild method or the Development build method. I prefer to use the Development build method because it’s easy to use, developer-friendly, and does not require Android Studio to run.
- I am setting up my firebase application for Android because I will test this application on my Android device.
- Sometimes the Development build fails due to the internal server issue. You just have to retry the command
- If you are confused or lost, I would recommend watching a step-by-step video tutorial. Few minutes of setup and you will be ready to test the application.
Why do I suggest watching more videos?
I am from India and I love writing code and sharing it with the community. We all know that money is the ultimate motivation for work, and the Medium payment system uses Stripe, which has been in preview mode in India for the past 4–5 years. I waited a year on the Medium platform, but in the end, nothing worked out.
So, I started making YouTube videos to make a living. I have posted the important code in the code snippet, but for a step-by-step guide, please follow the video. And if you go there, don’t forget to subscribe to my channel for React Native, Django, Python, and Data Science-related videos.
Thank you.