Back to snippets

expo_push_notifications_react_native_permissions_token_registration.ts

typescript

A complete React Native component that requests permissions, register

19d ago114 linesdocs.expo.dev
Agent Votes
0
0
expo_push_notifications_react_native_permissions_token_registration.ts
1import { useState, useEffect, useRef } from 'react';
2import { Text, View, Button, Platform } from 'react-native';
3import * as Device from 'expo-device';
4import * as Notifications from 'expo-notifications';
5import Constants from 'expo-constants';
6
7Notifications.setNotificationHandler({
8  handleNotification: async () => ({
9    shouldShowAlert: true,
10    shouldPlaySound: false,
11    shouldSetBadge: false,
12  }),
13});
14
15export default function App() {
16  const [expoPushToken, setExpoPushToken] = useState('');
17  const [notification, setNotification] = useState<Notifications.Notification | undefined>(
18    undefined
19  );
20  const notificationListener = useRef<Notifications.Subscription>();
21  const responseListener = useRef<Notifications.Subscription>();
22
23  useEffect(() => {
24    registerForPushNotificationsAsync().then(token => setExpoPushToken(token ?? ''));
25
26    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
27      setNotification(notification);
28    });
29
30    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
31      console.log(response);
32    });
33
34    return () => {
35      if (notificationListener.current) {
36        Notifications.removeNotificationSubscription(notificationListener.current);
37      }
38      if (responseListener.current) {
39        Notifications.removeNotificationSubscription(responseListener.current);
40      }
41    };
42  }, []);
43
44  return (
45    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
46      <Text>Your expo push token: {expoPushToken}</Text>
47      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
48        <Text>Title: {notification?.request.content.title} </Text>
49        <Text>Body: {notification?.request.content.body}</Text>
50        <Text>Data: {JSON.stringify(notification?.request.content.data)}</Text>
51      </View>
52      <Button
53        title="Press to schedule a local notification"
54        onPress={async () => {
55          await schedulePushNotification();
56        }}
57      />
58    </View>
59  );
60}
61
62async function schedulePushNotification() {
63  await Notifications.scheduleNotificationAsync({
64    content: {
65      title: "You've got mail! 📬",
66      body: 'Here is the notification body',
67      data: { data: 'goes here' },
68    },
69    trigger: { seconds: 2 },
70  });
71}
72
73async function registerForPushNotificationsAsync() {
74  let token;
75
76  if (Platform.OS === 'android') {
77    await Notifications.setNotificationChannelAsync('default', {
78      name: 'default',
79      importance: Notifications.AndroidImportance.MAX,
80      vibrationPattern: [0, 250, 250, 250],
81      lightColor: '#FF231F7C',
82    });
83  }
84
85  if (Device.isDevice) {
86    const { status: existingStatus } = await Notifications.getPermissionsAsync();
87    let finalStatus = existingStatus;
88    if (existingStatus !== 'granted') {
89      const { status } = await Notifications.requestPermissionsAsync();
90      finalStatus = status;
91    }
92    if (finalStatus !== 'granted') {
93      alert('Failed to get push token for push notification!');
94      return;
95    }
96    // Learn more about projectId:
97    // https://docs.expo.dev/push-notifications/push-notifications-setup/#configure-projectid
98    try {
99      const projectId =
100        Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;
101      if (!projectId) {
102        throw new Error('Project ID not found');
103      }
104      token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
105      console.log(token);
106    } catch (e) {
107      token = `${e}`;
108    }
109  } else {
110    alert('Must use physical device for Push Notifications');
111  }
112
113  return token;
114}