import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
[Link]({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
}),
});
function handleRegistrationError(errorMessage) {
alert(errorMessage);
throw new Error(errorMessage);
}
async function registerForPushNotificationsAsync() {
if ([Link] === 'android') {
[Link]('default', {
name: 'default',
importance: [Link],
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
if ([Link]) {
const { status: existingStatus } = await [Link]();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await [Link]();
finalStatus = status;
}
if (finalStatus !== 'granted') {
handleRegistrationError('Permission not granted to get push token for push
notification!');
return;
}
const projectId =
Constants?.expoConfig?.extra?.eas?.projectId ??
Constants?.easConfig?.projectId;
if (!projectId) {
handleRegistrationError('Project ID not found');
}
try {
const pushTokenString = (
await [Link]({
projectId,
})
).data;
[Link](pushTokenString);
return pushTokenString;
} catch (e) {
handleRegistrationError(`${e}`);
}
} else {
handleRegistrationError('Must use physical device for push notifications');
}
}
export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [notification, setNotification] = useState<[Link] |
undefined>(
undefined
);
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => {
registerForPushNotificationsAsync()
.then(token => setExpoPushToken(token ?? ''))
.catch((error: any) => setExpoPushToken(`${error}`));
[Link] =
[Link](notification => {
setNotification(notification);
});
[Link] =
[Link](response => {
[Link](response);
});
return () => {
[Link] &&
[Link]([Link]);
[Link] &&
[Link]([Link]);
};
}, []);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-
around' }}>
<Text>Your Expo push token: {expoPushToken}</Text>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text>Title: {notification && [Link]} </Text>
<Text>Body: {notification && [Link]}</Text>
<Text>Data: {notification &&
[Link]([Link])}</Text>
</View>
</View>
);
}