CodeBlanks Logo Icon CodeBlanks

Summary - Push notifications

Combine token, local and remote notifications to write a notification system.

Summary - Notifications

In this group you learned to install the expo-notifications package, get a push token, schedule a local notification, send a remote notification from the server and listen to notification events. Notifications are a powerful channel that reaches the user even when the app is closed.

In the summary we will combine three pieces: token registration, local notification scheduling and event listener setup. Together they form a real notification flow. Let us now merge them in a single app.

Practice Schedule a reminder

Complete the scheduleReminder function. Call Notifications.scheduleNotificationAsync. Pass content: {{ title: 'Reminder', body: 'Time is up', data: {{ taskId: 42 }} }} and trigger: {{ seconds: 30 }}. Await the call.

Starter code

App.js
import * as Notifications from 'expo-notifications';

export async function scheduleReminder() {
  // schedule a task notification thirty seconds from now
}

Sample solution

App.js
await Notifications.scheduleNotificationAsync({
  content: { title: 'Reminder', body: 'Time is up', data: { taskId: 42 } },
  trigger: { seconds: 30 },
});

Practice Set up a listener in useEffect

Complete the empty useEffect. Set up a response listener with const sub = Notifications.addNotificationResponseReceivedListener((response) => console.log(response.notification.request.content.data)). Clean it up with return () => sub.remove();. Use an empty dependency array [].

Starter code

App.js
import React from 'react';
import * as Notifications from 'expo-notifications';

export function useReminderTap() {
  React.useEffect(() => {
    // set up a response listener and return cleanup
  }, []);
}

Sample solution

App.js
const sub = Notifications.addNotificationResponseReceivedListener((response) => {
  console.log(response.notification.request.content.data);
});
return () => sub.remove();

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the token function

Question
const token = await Notifications.____({ projectId: 'my-project' });
Answer
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'my-project' });

Explanation: This function returns an Expo token.

2 Match each flow part to its role

Term Meaning
getExpoPushTokenAsync Gets the token
scheduleNotificationAsync Schedules a local
addNotificationReceivedListener Listens to events
sub.remove() Removes the listener

All lessons in Advanced