Ad

Handling Notification Responses In An Elegant Manner - React Native

Im trying to setup notifications in React Native(0.55.4), Im using react navigation to render my screens. Every thing is setup and I am receiving notifications and am able to read the payload

I referred to the following page to understand how response is received -
https://rnfirebase.io/docs/v5.x.x/notifications/receiving-notifications

I would like to know how I can incorporate this such that an event is called in any page of my react navigation whenever a notification is received, or it is called in the background and handled based on payload.

Currently its running only in the constructor and ComponentWillMount and other generic callbacks, but I would like it a function be called every time I receive a notification irrespective of what page I am on.

Ad

Answer

What you're looking for is the concept of a Subject. You need to essentially broadcast events at the place in your application where you receive the notification. Any screens you've set up that are interested in notifications can then register to listen to those events. Here's a basic Subject implemented in JS that I use in production to do exactly what you're describing.

const _handlers = {}

const Subject = {
  subscribe (...args) {
    const [event, handler] = args

    if (!_handlers[event]) _handlers[event] = []
    _handlers[event].push(handler)
  },
  unsubscribe (...args) {
    const [event, handler] = args

    if (!_handlers[event]) return
    _handlers[event] = _handlers[event].filter(func => func !== handler)
  },
  next (...args) {
    const [event, value] = args

    if (!_handlers[event]) return
    _handlers[event].forEach(handler => {
      if (typeof handler === 'function') {
        handler(value)
      }
    })
  }
}

Object.freeze(Subject)

module.exports = Subject

You can use it in your components like this:

notificationHandler = (payload) => {
  // Do something with the payload in your screen
}

componentDidMount () {
  Subject.subscribe('notification_received', this.notificationHandler)
}

componentWillUnmount () {
  Subject.unsubscribe('notification_received', this.notificationHandler)
}

When you receive a notification, your notification listener can call Subject.next('notification_received', payload)

Ad
source: stackoverflow.com
Ad