OneSignal / react-onesignal

React OneSignal Module: Make it easy to integrate OneSignal with your React App!
Other
74 stars 23 forks source link

[question]: Async functions stay pending when testing in localhost #112

Closed bolanos-nava closed 1 year ago

bolanos-nava commented 1 year ago

How can we help?

I set up a React test app on localhost:3000 and I configured my OneSignal app in the dashboard with the option ". I'm doing the following:

  1. Check if the OneSignal service worker isn't installed yet, and if it isn't, initialize OneSignal.
  2. After the init promise resolves, set the external user ID and show the category prompt.
  3. Then, I have a button to obtain the player ID. That button sets a state variable and triggers a useEffect, which calls the getUserId() method.

When the browser isn't subscribed to notifications and the OneSignal service worker isn't installed yet, I click on the allow button of the native prompt and then, without refreshing, click on the button to get the player ID, I can log it to the console without issue. However, when I refresh the page, I can no longer obtain the player ID because the async getUserId() method stays pending forever.

I have two questions:

  1. Is there some step I am missing when using the async methods of the SDK in a local testing environment?
  2. When I log the player ID to the console I don't see any network request done to the OneSignal API. Is it normal behavior?

I uploaded the test app to a repository here so you can check it out. You just have to put your app id in the constants object of the App.jsx file.

bolanos-nava commented 1 year ago

The async functions staying pending forever were due to not running OneSignal.init on every refresh.

When I first set up my test app, I got the window.Onesignal already defined as an object error, which I thought was due to running init on every refresh, so I added a function to check if the service worker was installed and if it was, skip the initialization. However, doing so prevented the OneSignal web SDK functions from loading and made window.OneSignal undefined. And the window.OneSignal already defined... error was due to React strict mode making the app render twice.

I think it would be good to add a check in the React SDK to see if window.OneSignal is defined and throw an error or warning if it is not.