schmoove
schmoove

Reputation: 502

React Native: Call a function from tapping a Push Notification?

So I want to drop the user into a specific navigator scene when they tap an incoming push notification. The "scene" and the "id" used are passed in the notification payload as JSON.

But I have no idea what to do with these values inside the

PushNotificationIOS.addEventListener('notification', this._onNotification.bind(this));

"notification" event.

Obviously the app appears when tapping the notification, but how to I fire a function once it does?

Thanks!!

Upvotes: 4

Views: 1708

Answers (1)

damusnet
damusnet

Reputation: 4398

In your topmost component, the one registered in your index.ios.js, in the componentDidMount method, you can add your listener and get the data from the notification:

export default class App extends Component {
    componentDidMount() {
        PushNotificationIOS.addEventListener('notification', this._onNotification.bind(this));
        if (notification) {
            const data = notification.getData();
            if (data) {
                // do your thing
            }
        }
    }
}

Another solution would be to pass a url, and to implement the following code, also in your topmost component's componentDidMount method:

Linking.getInitialURL().then(url => {
  if (!url) {
    return null;
  }
  // do something to decide which component to load
  navigator.push({
    component: YourComponent,
    passProps: {
      // your props
    },
  });
  return null;
}).catch(() => null);

Upvotes: 1

Related Questions