0

1 year ago, I got pushToken successfully in my react-native app. But right now official website sample code was changed, so I couldn't find any code how to get pushToken.

This is the code I used last year. (Class component)

constructor(props) {
    super(props);
    ...
    OneSignal.addEventListener('ids', this.onIds);
}
componentWillUnmount() {
    OneSignal.removeEventListener('received', this.onReceived);
    OneSignal.removeEventListener('opened', this.onOpened);
    OneSignal.removeEventListener('ids', this.onIds);
}
onIds(device) {
    console.log('Device info: ', device);  // I got pushToken here successfully last year.
}

This is my current code. (Functional component)

useEffect(() => {
    // OneSignal Init Code
    OneSignal.setAppId("My-OneSignal-Key");
    OneSignal.setLogLevel(6, 0);
    // END OneSignal Init Code

    // Prompt for push on iOS
    OneSignal.promptForPushNotificationsWithUserResponse(response => {
        console.log("Prompt response:", response);
    });

    // Method for handling notifications received while app in foreground
    OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
        console.log("OneSignal: notification will show in foreground:", notificationReceivedEvent);
        let notification = notificationReceivedEvent.getNotification();
        console.log("notification: ", notification);
        const data = notification.additionalData
        console.log("additionalData: ", data);
        // Complete with null means don't show a notification.
        notificationReceivedEvent.complete(notification);
    });

    // Method for handling notifications opened
    OneSignal.setNotificationOpenedHandler(notification => {
        console.log("OneSignal: notification opened:", notification);
    });
}

But now, where should I get pushToken?

SatelBill
  • 641
  • 2
  • 12
  • 28

2 Answers2

2

I found this in the doc:

const deviceState = await OneSignal.getDeviceState();

so I think it could be something like:

const deviceState = (await OneSignal.getDeviceState()).pushToken;
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
-1

Look inside the notification object of setNotificationOpenedHandler or setNotificationWillShowInForegroundHandler.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77