Created
August 19, 2019 18:25
-
-
Save helenaford/d33bd8e621575fd27d6bff65cf04226c to your computer and use it in GitHub Desktop.
React Native & Firebase: App.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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