React-native-push-notification: How to access "this" inside the onNotification?

Created on 5 Feb 2016  路  7Comments  路  Source: zo0r/react-native-push-notification

At first I had PushNotification.configure({ in index.android.js outside the class declaration but now I have it inside the componentDidMount, is anything wrong with this?

Now I want to have access to this.state inside the onNotification but I don't know how.

I tryed to add a PushNotification.addEventListener to an external method but the class doesn't accept it.

Most helpful comment

I know it麓s solved but here is a simpler way

      onRegister: (token) => {
        this.handleRegister(token);
      },

      // (required) Called when a remote or local notification is opened or received
      onNotification: (notification) => {
        this.handleNotification(notification);
      },

All 7 comments

Try bind its parent, ex:

componentDidMount: function() {
    PushNotification.configure({
          /* ... */
          onNotification: function(notification){
              console.log(this.state);
          }.bind(this),
          /* ... */
     });
}

The gives unexpected token on the line of the bind.

I tried also to bind the main function:

PushNotification.configure({
          /* ... */
          onNotification: function(notification){
              console.log(this.state);
          },
          /* ... */
     }.bind(this));

or

PushNotification.configure({
          /* ... */
          onNotification: function(notification){
              console.log(this.state);
          },
          /* ... */
     }).bind(this);

or even

  onNotification ((notification) => {
          . . .
        }).bind(this),

But every try returned an error.

Thats a syntax error, the bind must be attached to the function.

I didn't understand. Where is the syntax error? Where can I bind the parent?

Thanks.

@nbastoWM Try defining your notification handler as a method on your component, then binding the handler:

handleNotification: function(notification) {
  console.log(this.state);
}

componentDidMount: function() {
  PushNotification.configure({
    onNotification: this.handleNotification.bind(this)
  });
}

I know it麓s solved but here is a simpler way

      onRegister: (token) => {
        this.handleRegister(token);
      },

      // (required) Called when a remote or local notification is opened or received
      onNotification: (notification) => {
        this.handleNotification(notification);
      },

@mklb thanks so much..very2 appreciate.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ssolida picture ssolida  路  3Comments

uendar picture uendar  路  3Comments

anativ picture anativ  路  3Comments

Kiran0791 picture Kiran0791  路  3Comments

ahmadallo1 picture ahmadallo1  路  3Comments