Sending push notifications in React Native with Expo
We should first register the app to achieve a push notification token to use push notifications in a React Native application. In this situation, we’re going to employ Expo’s notifications API.
We will now create an async function in the AppNavigator component that will ask React Native Expo for a token.
async function registerForPushNotificationsAsync() {
let token;
const status = await Notifications.getPermissionsAsync(); let finalStatus = status .status ; if (existingStatus !== 'granted') { const status = await Notifications.requestPermissionsAsync(); finalStatus = status.status; } if (finalStatus !== 'granted') { alert('Failed to get device push token for push notification!'); return; } token = (await Notifications.getExpoPushTokenAsync()).data; console.log(token); return token; }
We must determine whether permission has been given; if not, we must display a warning about the error and promptly exit the function. The token is returned by the function if the token request procedure was successful. In addition, we now log the Expo token to the console for development needs.
For our application, we will utilize the use effect hook from React to invoke the aforementioned function:
import * as Device from ‘expo-device’;
import * as Notifications from ‘expo-notifications’;
import React, {useState, useEffect, useRef} from ‘react’;
import {Text, View, Button, Platform} from ‘react-native’;
Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowAlert: true, shouldPlaySound: false, shouldSetBadge: false, }), });
Export default function App() {
const [expoPushToken, setExpoPushToken] = useState(”);
const [notification, setNotification] = useState(false);
const notificationListener = useRef();
const responseListener = useRef();
useEffect(() => { registerForPushNotificationsAsync().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={{flex: 1, alignItems: 'center', justifyContent: 'space-around'}}> <Text>Your expo push token: {expoPushToken}</Text>{' '} <View style={{alignItems: 'center', justifyContent: 'center'}}> <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="Press to schedule a notification" onPress={async () => { await schedulePushNotification(); }} /> </View> ); }
Async function schedulePushNotification() {
await Notifications.scheduleNotificationAsync({ content: { title: "You've got mail! 📬", body: 'Here is the notification body', data: {data: 'goes here'}, }, trigger: {seconds: 2}, }); } async function registerForPushNotificationsAsync() { let token; if (Platform.OS === 'android') { await Notifications.setNotificationChannelAsync('default', { name: 'default', importance: Notifications.AndroidImportance.MAX, vibrationPattern: [0, 250, 250, 250], lightColor: '#FF231F7C', }); } if (Device.isDevice) { const {status: existingStatus} = await Notifications.getPermissionsAsync(); let finalStatus = existingStatus; if (existingStatus !== 'granted') { const {status} = await Notifications.requestPermissionsAsync(); finalStatus = status; } if (finalStatus !== 'granted') { alert('Failed to get device push token for push notification!'); return; } token = (await Notifications.getExpoPushTokenAsync()).data; console.log(token); } else { alert('Must use a physical device for Push Notifications'); } return token; }