reactjspush-notificationreact-nativeonesignal

How to save one signal player id in react native state


I am new to react native, I am using one signal for notification. I got one signal users player id from OneSignal.configure(); this and by following code which I have done but that player id which I can see only on console. I am using setState to save in state but it is showing error that setState is not a function. How can I get that player id to save it in state.

code:

componentWillMount() {
          OneSignal.init("d447e6e2-0c8e-4781-8292-6e77d2e86691");

          OneSignal.configure();
          OneSignal.addEventListener('received', this.onReceived);
          OneSignal.addEventListener('opened', this.onOpened);
          OneSignal.addEventListener('ids', this.onIds);
      }

      componentWillUnmount() {
          OneSignal.removeEventListener('received', this.onReceived);
          OneSignal.removeEventListener('opened', this.onOpened);
          OneSignal.removeEventListener('ids', this.onIds);
      }

      onReceived(notification) {
          console.log("Notification received: ", notification);
      }

      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);
      }

      onIds(device) {
        console.log('Device info: ', device);
      console.log('player id: ', device.userId);
       this.setState({
            pid: device.userId,
          })
       console.log(this.state.pid);
      }

Solution

  • The event listeners functions doesn't know your this so you have to use bind to take your this inside them.

    componentWillMount() {
        OneSignal.init('ONESIGNAL-APP-ID');
    
        OneSignal.addEventListener('received', this.onReceived.bind(this));
        OneSignal.addEventListener('opened', this.onOpened.bind(this));
        OneSignal.addEventListener('ids', this.onIds.bind(this));
        OneSignal.configure();
    }
    

    UPDATE

    You can also declare as arrow functions to avoid .bind(this):

    componentWillMount() {
        OneSignal.init('ONESIGNAL-APP-ID');
    
        OneSignal.addEventListener('received', this.onReceived);
        OneSignal.addEventListener('opened', this.onOpened);
        OneSignal.addEventListener('ids', this.onIds);
        OneSignal.configure();
    }
    
    onReceived = () => {}
    onOpened = () => {}
    onIds = () => {}