Skip to content

Instantly share code, notes, and snippets.

@helenaford
Created August 19, 2019 18:25
Show Gist options
  • Save helenaford/d33bd8e621575fd27d6bff65cf04226c to your computer and use it in GitHub Desktop.
Save helenaford/d33bd8e621575fd27d6bff65cf04226c to your computer and use it in GitHub Desktop.
React Native & Firebase: App.js
import React, { Component, Fragment } from 'react';
import firebase from 'react-native-firebase';
class App extends Component<Props> {
...
getToken = async () => {
let fcmToken = await AsyncStorage.getItem('fcmToken');
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
await AsyncStorage.setItem('fcmToken', fcmToken);
}
}
};
checkPermission = async () => {
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
this.getToken();
} else {
this.requestPermission();
}
};
requestPermission = async () => {
try {
await firebase.messaging().requestPermission();
this.getToken();
} catch (error) {
console.log('permission rejected');
}
};
createNotificationListeners = () => {
this.onUnsubscribeNotificaitonListener = firebase
.notifications()
.onNotification(notification => {
firebase.notifications().displayNotification(notification);
});
};
removeNotificationListeners = () => {
this.onUnsubscribeNotificaitonListener();
};
componentDidMount() {
// Build a channel
const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
.setDescription('My apps test channel');
// Create the channel
firebase.notifications().android.createChannel(channel);
this.checkPermission();
this.createNotificationListeners();
}
componentWillUnmount() {
this.removeNotificationListeners();
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment