Advanced: Notifications: SUCCESSFUL CODE

DEVELOPER NOTES:

******************************* Notification *****************************
My physical smartphone: Samsung Galaxy 6 (Android version: 7.0)
My Android Virtual Device: Pixel 2 (Note: Advanced Config: Boot option: Cold boot)

Providers -

  • Expo’s Push Notification Service <-----<<< Easiest without a lot of prep
  • One Signal
  • Firebase Cloud Messaging
  • Amazon’s Simple Notification Service (SNS)

INSTALL Expo Notifications -
$ expo install expo-notifications
added 8 packages from 6 contributors and audited 1098 packages in 4.433s

UPDATE -
app.json:
“android”: {
“useNextNotificationsApi”: true,
:

-Push Notification Tool — Expo
Tool to send test push notifications

******************* Mosh’s Notifications NOT working ***************
He is using:
import Notifications from ‘expo’;
It should be:
import * as Notifications from ‘expo-notifications’;

I used code from the following URLs to make Notification work SUCCESSFULLY.
-Notifications - Expo Documentation
-Push Notifications Overview - Expo Documentation … follow guide from here
-Sending Notifications with Expo's Push API - Expo Documentation
:
-Receiving Notifications - Expo Documentation
:
Tool to send a test Notification:
-Push Notification Tool — Expo

CODE: useNotifications.js

import { useEffect, useRef, useState } from "react";
import * as Notifications from 'expo-notifications';

import expoPushTokensApi from "../api/expoPushTokens";

// Required
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

export default useNotifications = () => {
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    registerForPushNotifications();

    // This listener is fired whenever a notification is received while the app is foregrounded
    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
        setNotification(notification);
    });

    // This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
        console.log(response.notification.request.content.body);
    });

    return () => {
        Notifications.removeNotificationSubscription(notificationListener.current);
        Notifications.removeNotificationSubscription(responseListener.current);
    };

}, []);

    
const registerForPushNotifications = async () => {
   try {
        const permissions = await Notifications.getPermissionsAsync();
        if (! permissions.granted) {
            const finalPermissions = await Notifications.requestPermissionsAsync();
            if (! finalPermissions.granted) {
                console.log("permissions NOT granted!");
                return;
            }
        }
        console.log("permissions granted!");

        const token = await Notifications.getExpoPushTokenAsync();
        expoPushTokensApi.register(token.data);

    } catch (error) {
        console.log("Error getting a push token", error);
    }
  };
}
5 Likes

Thanks for this! I was struggling so much

Would you mind sharing your repo for your source?
I’m trying to run the “Begin” source from Mosh’s Authentication section but it’s been a total mess with Expo updates…

Following up – @kasiliwachiye or @JerryC do you have a repo I where I can view the other files involved with notifications?

@j-sup I don’t have a repo setup yet but the rest of the code is in the ‘end’ folder of the resources from Mosh. You can watch the videos through to make sense of it all but what JerryC is showing us is the finished hooks/useNotifications.js . Mosh moves all the code out of AppNavigator to a hook but JerryC is the code you need to replace it with.

Then in AppNavigor.js here is the relevant section

import NewListingButton from './NewListingButton';

import useNotifications from '../hooks/useNotifications';

const Tab = createBottomTabNavigator();

const AppNavigator = () => {

  useNotifications();

  return (

    <Tab.Navigator

As you can see we move everything out of AppNavigator, replace it all with JerryC hooks/useNotifications.js, then in AppNavigator import and call the hook.

Add Mosh api/expoPushTokens.js from the resources which is imported and used in hooks/useNotifications.js

This will get notifications working. Don’t forget to add the ‘useNextNotificationsApi’ part to your app.json file. I’m not sure what it does (havn’t looked it up yet) but JerryC says add it so I did. Here is my android section

"android": {

      "useNextNotificationsApi": true,

      "adaptiveIcon": {

        "foregroundImage": "./app/assets/adaptive-icon.png",

        "backgroundColor": "#e634b"

      }

    },

For the navigation video when clicking on a notification copy Mosh in app.js and navigation/rootNavigation.js but for the listener in hooks/useNotifications.js
import navigation from '../navigation/rootNavigation';
And then do navigation in the responseListener

// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)

    responseListener.current =

      Notifications.addNotificationResponseReceivedListener(response => {

        console.log(response.notification.request.content.body);

        navigation.navigate('AccountNav');

      });

I called my Tab.Screen ‘AccountNav’ instead of ‘Account’ because of a issue I had back when we were creating the embedded navigators where it complained about duplicate names.

I just got this working. Thanks @JerryC

Hope this additional info is helpful @j-sup

Says here app.json / app.config.js - Expo Documentation
that useNextNotifications is deprecated. I removed it from my app.json and everything still works.

Hello everyone,

I’m getting this error for ‘result.ok’ after completing the contact seller section. I’m unable to successfully make a call for the notification :frowning: . Please help.

Warning: An unhandled error was caught from submitForm(), [TypeError: undefined is not an object (evaluating 'result.ok')]
at node_modules/formik/dist/formik.cjs.development.js:957:17 in useEventCallback$argument_0

thank you!

1 Like