0

I have installed the OneSignal package on my react native application and want to insert the notification to my state so the notification is accessable within to class.

So, I tried to do this so far:

import OneSignal from "react-native-onesignal";

export default class SuperScreen extends Component {
    constructor(props) {
    super(props);
    this.state = {
      showPopup: false,
      pushNotification: null
    };

    OneSignal.init("<mykey>", {kOSSettingsKeyAutoPrompt: true});
    OneSignal.inFocusDisplaying(0);

    OneSignal.addEventListener("opened", this.onOpened);
    OneSignal.addEventListener("ids", this.onIds);
}

componentWillUnmount() {
    OneSignal.removeEventListener("opened", this.onOpened);
}

onOpened(openResult) {
    console.log("Message: ", openResult.notification.payload.body);
    console.log("Data: ", openResult.notification.payload.additionalData);
    console.log("isActive: ", openResult.notification.isAppInFocus);
    console.log("openResult: ", openResult);

    this.setState({ pushNotification: openResult});
}

But I always get this.setState(...) is not a function. So I added modified the line to this:

this.setState({ pushNotification: openResult}).bind(this);

However, I still get the same result.. I just want to update the state. Can you guys explain me why I am getting this error message and how can I fix it?

Kind regards and Thank You!

1 Answer 1

4

That error is happening because onOpened is not bound to the class component so the value of this inside onOpenedis not the one you expect (it's just null).

In order to fix it you can use class properties + an arrow function

onOpened = (openResult) => {
    console.log("Message: ", openResult.notification.payload.body);
    console.log("Data: ", openResult.notification.payload.additionalData);
    console.log("isActive: ", openResult.notification.isAppInFocus);
    console.log("openResult: ", openResult);

    this.setState({ pushNotification: openResult});
}

or you can bind it in the constructor using .bind(this)

 constructor(props) {
    super(props);
    this.state = {
      showPopup: false,
      pushNotification: null
    };

    this.onOpened = this.onOpened.bind(this); // <--- here

    OneSignal.init("<mykey>", {kOSSettingsKeyAutoPrompt: true});
    OneSignal.inFocusDisplaying(0);

    OneSignal.addEventListener("opened", this.onOpened);
    OneSignal.addEventListener("ids", this.onIds);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.