How to know if firebase.messaging().requestPermission has been previously called using react-native-firebase

Viewed 2526

I have a React Native app that uses Firebase Cloud Messaging with the react-native-firebase package.

I am doing this on the first screen of a React Native app, so after 5 seconds, the user will be sent to a new screen which explains why push notifications are useful, and gives them a button to launch the dialog where they can accept or decline the permission.

setTimeout(() => {

            firebase.messaging().hasPermission()
                .then(enabled => {
                    if (enabled) {
                        // user has permissions
                    } else {
                        // user doesn't have permission
                        this.props.navigation.navigate('EnableNotificationPermissionScreen')
                    }
                });

        },
            5000);

In the EnableNotificationPermissionScreen screen, there is a button like this:

 <Button onPress={this.onSetNotificationPref.bind(this)} title="Set Notification Preference" color="#4ab2fc"/>

Which is handled by an event like this:

onSetNotificationPref() {

        firebase.messaging().requestPermission()
            .then(() => {
                // User has authorized
                firebase.analytics().logEvent('messaging_permission_accepted');

                this.props.navigation.navigate('App');
            })
            .catch(error => {
                // User has rejected permissions
                firebase.analytics().logEvent('messaging_permission_rejected');

                this.props.navigation.navigate('App');
            });
    }

If the user accepts, everything works as I would hope, and the user will have the permission, and will not navigate to that screen again.

However, if the user rejects the permission, I do not want to navigate them to that screen again. As-is, they will be navigated there again because hasPermission will be false. Also, clicking the button to execute requestPermission on that screen will do nothing, as the OS will block requestPermission().

In the examples I have seen, requestPermission is called whenever the permission is not enabled (with no custom screen like this); and so either the dialog pops up, or it doesn't. However, in the flow that I am trying to achieve, I want to navigate to this custom screen only if the user does not have permission because they have not been asked. If they have been asked and declined, they should not be navigated to that screen.

Is there any way to achieve that using the functions in firebase.messaging(), or do I have to use persistent storage like async-storage to track on my own whether the dialog has been shown?

0 Answers
Related