Hello everyone, I am having issues with Push Notification with expo. I don’t know how to generate ExponentPushToken. This is my code (any error, correction will be needed ).
I will appreciate your assistance
import React, { Component } from “react”;
import { Text, View, Button, Vibration, Platform } from ‘react-native’;
import { Notifications } from ‘expo’;
import * as Permissions from ‘expo-permissions’;
import Constants from ‘expo-constants’;
import * as firebase from “firebase”;
class Notification extends Component{
state = {
expoPushToken: '',
notification: {},
};
registerForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = await Notifications.getExpoPushTokenAsync();
console.log(token);
let uid = firebase.auth().currentUser.uid;
firebase.database().ref("users").child(uid).update({ expoPushToken: token });
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.createChannelAndroidAsync('default', {
name: 'default',
sound: true,
priority: 'max',
vibrate: [0, 250, 250, 250],
});
}
};
componentDidMount() {
this.registerForPushNotificationsAsync();
//this.notificationSubscription = Notifications.addListener(this._handleNotification);
}
// _handleNotification = notification => {
// Vibration.vibrate();
// console.log(notification);
// this.setState({ notification: notification });
// };
// // Can use this function below, OR use Expo’s Push Notification Tool-> Push Notification Tool — Expo
// sendPushNotification = async () => {
// const message = {
// to: this.state.expoPushToken,
// sound: ‘default’,
// title: ‘Original Title’,
// body: ‘Hello is the nigeria!’,
// data: { data: ‘goes here’ },
// _displayInForeground: true,
// };
// //},
// const response = await fetch(‘https://exp.host/--/api/v2/push/send’ ,{
// method: ‘POST’,
// headers: {
// Accept: ‘application/json’,
// ‘Accept-encoding’: ‘gzip, deflate’,
// ‘Content-Type’: ‘application/json’,
// },
// body: JSON.stringify(message),
// });
// };
render() {
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
}}>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text>Origin: {this.state.notification.origin}</Text>
<Text>Data: {JSON.stringify(this.state.notification.data)}</Text>
</View>
</View>
);
}
}
export default Notification;