Reputation: 71
i'm trying to use oneSignal. I follow the steps from the documentation. when I run the app, it should console the device information according to this code in my index.js :
constructor(properties) {
super(properties);
// OneSignal.init("e353b33e-8b5f-4093-8a86-073b0504b5f2");
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('registered', this.onRegistered);
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);
}
when I open the console, it didn't show the device information from the function onIds().
can someone tell me what i'm doing wrong? i'm new to this so thanks for your help
Upvotes: 0
Views: 2374
Reputation: 430
For me, OneSignal.getDeviceState() didn’t work, even though I was using the latest version. Instead, I used the following approach, which successfully retrieves both the OneSignal user ID and the subscription ID:
// Opt-in for push notifications
await OneSignal.User.pushSubscription.optIn();
try {
// Get the OneSignal User ID
const userId = await OneSignal.User.getOnesignalId();
setOnesignalUserId(userId);
console.log('OneSignal User ID:', userId);
// Handle subscription changes
OneSignal.User.pushSubscription.addEventListener('change', subscription => {
const subscriptionId = subscription?.current?.id;
if (subscriptionId) {
setSubscriptionId(subscriptionId);
console.log('OneSignal Subscription ID:', subscriptionId);
} else {
console.log('OneSignal Subscription ID is not available yet.');
}
});
} catch (error) {
console.error('Error with OneSignal setup:', error);
}
I hope this solution works for you! Feel free to reach out if you need further assistance.
Upvotes: 0
Reputation: 1279
This worked for me in functional component:
const data = await OneSignal.getDeviceState();
const player_id=data.userId;
Upvotes: 2
Reputation: 1
I've just encountered this issue and it's quite unclear but if you check the docs they say:
Please note that calling OneSignal.configure() causes the ids event to fire.
I just added OneSignal.configure() at the end of the constructor and now it triggers onIds().
Upvotes: 0