Skip to content

[Question]: How can I ensure sync of optedIn state? #175

Open
@tonypizzicato

Description

@tonypizzicato

How can we help?

I am trying to integrate OneSignal but cannot understand how to reliably sync local indexDB state with with the server. I am building a custom preferences page, where user can:
a) subscribe/unsubscribe to web push or email notifications;
b) subscribe/unsubscribe to different notification types, like news, recommendations, security, etc. I'm using tags for it and it works fine so far.

I am testing an a) flow with a simple optedIn toggle function which changes opted in state. As far as I understood web sdk has a queue under the hood which periodically syncs the state with the platform. The problem is when I call await OneSignal.User.PushSubscription.optIn(); the OneSignal.User.PushSubscription.optedIn state updates synchronously. But if I reload my app before it was synced with the platform, I'm stuck in:
a) inconsistent state, so I do not know the actual state of the subscription and don't know the state of the "Push" toggle in the UI;
b) a state where I am able to send push notifications to unsubscribed users.

Is there a way to ensure the delivery of those messages to the platform?

My test function:

  const toggleOptIn = async () => {
    if (!initialized) {
      console.error('OneSignal is not initialized');
      return;
    }
    try {
      const isOptedIn = OneSignal.User.PushSubscription.optedIn;
      console.log('----------------> Toggling OneSignal opt-in:', isOptedIn);
      if (isOptedIn) {
        await OneSignal.User.PushSubscription.optOut();
      } else {
        await OneSignal.User.PushSubscription.optIn();
      }
    } catch (error) {
      console.error('Error toggling OneSignal opt-in:', error);
    }

    return OneSignal.User.PushSubscription.optedIn;
  };

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions