import React,{useEffect, useRef, useState} from 'react';
import {StyleSheet, Text, Button, View} from 'react-native';
import * as Notifications from 'expo-notifications';
import registerForPushNotifications from './push_notifications';
Notifications.setNotificationHandler({
handleNotification: async () => {
shouldShowAlert:true;
shouldPlaySound:true;
shouldSetBadge:true;
}
});
export default function App(){
const [expoPushToken, setExpoPushToken] = useState("");
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
useEffect(()=>{
registerForPushNotifications().then((token)=> setExpoPushToken(token));
notificationListener.current = Notifications.addNotificationReceivedListener((notification)=>{
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener((response)=>{
console.log(response);
});
return ()=>{
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
}
},[]);
return (
<View style="styles.container">
<Text>Your Token: {expoPushToken}</Text>
<Text>Title: {notification && notification.request.content.title}</Text>
<Text>Body: {notification && notification.request.content.body}</Text>
<Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
</View>
<Button title="Send one" onPress={async ()=>{await sendPushNotification(expoPushToken)}} />
);
}
async function sendPushNotification(expoPushToken){
const message ={
to:expoPushToken,
sound:'default',
title:'Hi',
body:'There',
data:{someData:"goes here"}
}
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),
});
}