How to Scheduled Push Notification with Firebase in React Native 
Tags: reactnative, firebase, react, notification
Published: 2020-05-18 11:04:37

---
description: Struggling with react native development to schedule push notifications with firebase? Here's a comprehensive guide for react native app developers to schedule push notifications using firebase
---

Hello folks. I hope you all are doing well.

In this tutorial, you're going to learn how to handle and schedule local push notification with firebase using [react native development](https://www.botreetechnologies.com/react-native-development). 
There are two types of notifications, remote and local notifications.
#### Remote Notifications

With remote notifications, we should use one of our company servers to push data to user devices via any notification service.

#### Local Notifications

In local notification, notification is scheduled and triggered by an app on a particular time and date and delivered on the same device.
In this tutorial, we will use local notification to schedule reminder.

## Prerequisites 

This tutorial requires basic knowledge of React Native development. To set up your development machine, follow the official guide [here](https://facebook.github.io/react-native/docs/0.59/getting-started).

We are going to use [react-native-firebase](https://github.com/invertase/react-native-firebase) to handle push notification 

Before implementing to schedule push notification, please visit this [article](https://dev.to/botreetechnologies/how-to-implement-push-notification-with-firebase-in-react-native-2e7n) to configure project.
After the configured project, Let's create one **FCMService** to handle notification  

Create one folder in project directory named it as ``src`` and under the ``src`` folder create one file name as ``FCMService.js``  

Before use push notification in the app, we require the user permission to display notifications in the app. If the user denies permission it explicitly changes from the settings.

First, let's write below code in FCMService.js to get permission from the user 

```javascript
 checkPermission = (onRegister) => {
    firebase.messaging().hasPermission()
      .then(enabled => {
        if (enabled) {
          //user has permission
          this.getToken(onRegister)
        } else {
          //user don't have permission
          this.requestPermission(onRegister)
        }
      }).catch(error => {
        console.log("Permission rejected", error)
      })
  }

  getToken = (onRegister) => {
    firebase.messaging().getToken()
      .then(fcmToken => {
        if (fcmToken) {
          onRegister(fcmToken)
        } else {
          console.log("User does not have a device token")
        }
      }).catch(error => {
        console.log("getToken rejected ", error)
      })
  }

  requestPermission = (onRegister) => {
    firebase.messaging().requestPermission()
      .then(() => {
        this.getToken(onRegister)
      }).catch(error => {
        console.log("Requested persmission rejected ", error)
      })
  }

  deletedToken = () => {
    firebase.messaging().deleteToken()
      .catch(error => {
        console.log("Delected token error ", error)
      })
  }
```


After getting permission from the user we will create listeners for listen notification.

```javascript
createNoitificationListeners = (onRegister, onNotification, onOpenNotification) => {
    
    // This listener triggered when notification has been received in foreground
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      onNotification(notification)
    })

    // This listener triggered when app is in backgound and we click, tapped and opened notifiaction
    this.notificationOpenedListener = firebase.notifications()
      .onNotificationOpened((notificationOpen) => {
        console.log(notificationOpen)
        if (notificationOpen) {
          const notification = notificationOpen.notification
          onOpenNotification(notification)
          this.removeDelieveredNotification(notification)
        }
      })

    // This listener triggered when app is closed and we click,tapped and opened notification 
    firebase.notifications().getInitialNotification()
      .then(notificationOpen => {
        if (notificationOpen) {
          const notification = notificationOpen.notification
          onOpenNotification(notification)
          this.removeDelieveredNotification(notification)

        }
      })

    // Triggered for data only payload  in foreground 
    this.messageListener = firebase.messaging().onMessage((message) => {
      onNotification(message)
    })

    // This listener triggered when new token 
    this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
      console.log("FCM new token: ", fcmToken)
      onRegister(fcmToken)
    })
  }
```
###Read More: [Implement Push Notification with Firebase in React Native](https://dev.to/botreetechnologies/how-to-implement-push-notification-with-firebase-in-react-native-2e7n)

#### Create Android Notification Channel
As of Android 8.0 (API Level 26), notifications must specify a Notification Channel or they will not appear. To allow [React Native App Developers](https://www.botreetechnologies.com/hire-react-native-developers) for Integrating Firebase to work seamlessly across all versions of Android, we will create ``buildChannel()`` before we build notification.

```javascript
buildChannel = (obj) => {
    return new firebase.notifications.Android.Channel(
      obj.channelId, obj.channelName,
      firebase.notifications.Android.Importance.High)
      .setDescription(obj.channelDes)
  }
```

Build channel in android accepts three parameters `channelId`, `name` and `importance`. 

Now, we’ll add buildNotification() method which will build a notification when a notification is received:

```javascript
buildNotification = (obj) => {
    console.log(obj)
    firebase.notifications().android.createChannel(obj.channel)

    const notification = new firebase.notifications.Notification()
      .setSound(obj.sound)
      .setNotificationId(obj.dataId)
      .setTitle(obj.title)
      .setBody(obj.content)
      .setData(obj.data)
      .android.setChannelId(obj.channel.channelId)
      .android.setLargeIcon(obj.largeIcon)
      .android.setSmallIcon(obj.smallIcon)
      .android.setColor(obj.colorBgIcon)
      .android.setPriority(firebase.notifications.Android.Priority.High)
      .android.setVibrate(obj.vibrate)
      .android.setAutoCancel(true)
    
   return notification
}
```

Let's create one function that displays notifications when a notification arrives.

```javascript
displayNotification = (notification) => {
    firebase.notifications().displayNotification(notification)
      .catch(error => { console.log("Display Notification error", error) })
  }
```

Whenever we open a notification and displays a notification after that we need to remove delivered notification so, we create 

`removeDelieveredNotification()`
```javascript
removeDelieveredNotification = (notification) => {
    firebase.notifications()
      .removeDeliveredNotification(notification.notificationId)
  }
```
The Purpose of this tutorial is to schedule notification so, Let's create `scheduleNotificaion()`
```javascript
  scheduleNotification = (notification, datetime) => {
    const date = new Date(datetime)
    firebase.notifications()
      .scheduleNotification(notification, { fireDate: date.getTime() })
  }
```

So, Final `FCMService.js` looks like this 
{% gist https://gist.github.com/RajanTank/32a31c79eba7d33551f1d4d0ad072385 %}

Before proceeding further Please install this dependency  
```
$ npm install react-native-elements react-native-modal-datetime-picker moment @react-native-community/datetimepicker react-native-vector-icons   
```
So, we have created one file under `src` folder `scheduleReminder.js`
Let's write below code into `scheduleReminder.js` file 

{% gist https://gist.github.com/RajanTank/e49611311266b26424cda005e6471f11 %}
On `componentDidMount()` we have register our fcmservice and link listener callback function we have link three function `onRegister()`, `onNotification()` and `onOpenNotification()`.  

`onRegister` function we have got the user permission, `onNotification` function called when our app is opened and any notification arrives that time onNotification function creates a notification and displays the notification and `onOpenNotification` function called whenever you tap and open the notification. 

We get time, title and description from the user to schedule a reminder, before a schedule reminder we need to create a notification object by using `buildNotification()` of FCMService because a FCMService's `scheduleNotification()` function accepts a parameter as notification object and date & time.  

After configuring all things now it's time to test the app 
{% gist https://gist.github.com/RajanTank/4f7e548d1c98763c9cf45f877b3387af %}

Find the source code in the [Github repo](https://github.com/RajanTank/RNPushNotification) here.

###[Click here to read more about](https://www.botreetechnologies.com/react-native-development)