React Native Push Notifications Approach

I’m using the React Native SDK but building my own UI.
What’s the recommended approach for getting push notifications working now?

Can I get the direct push working or do I need to build a service and use the webhook approach?

Hello @BenGannaway,

Thanks for reaching out. Since you’re using the React Native SDK and building your own UI, you can get direct push notifications working by registering the device token using our API.

Please refer to the following API endpoint for registration:
:link: Register Device for Notification

You can use the following sample code:

if (fcmToken) {
  try {
    fetch(`${apiEndpoint}/v1/notification`, {
      method: 'POST',
      headers: {
        'X-API-KEY': apiKey,
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        deviceId: generateUUID(),
        platform: Platform.OS,
        userId: userId,
        token: fcmToken,
      }),
    }).catch((err) => console.error(err));
  } catch (err) {
    console.log(err);
  }
}

This approach does not require building a separate service or using the webhook setup. Let us know if you need help with the integration.

Thanks, do I still need to go through the Firebase setup etc described here:

Hello @BenGannaway, yes, that’s correct. You’ll still need to follow the setup steps outlined in the documentation.

So I think I’ve set up everything according to the docs. I can hit the endpoint as you suggested above and it comes back ok.

In my console I can see it subscribing to a load of feeds. I’m not 100% sure that’s related but it looks like it is.

But I’m still not seeing any notiifications. What else do I need to add?

Or what can I do to debug this?

Hello @BenGannaway , on which platform are you not receiving the push notification — iOS or Android?

I’m testing iOS at the moment. My implementation below:

import { useCallback, useEffect, useState } from 'react';
import { PermissionsAndroid, Platform } from 'react-native';
import Config from 'react-native-config';
import uuid from 'react-native-uuid';
import { useAuth } from 'store';

import messaging from '@react-native-firebase/messaging';

const generateUUID = async () => {
  const id = uuid.v4();
  return id;
};

export const useSocialNotifications = () => {
  const apiEndpoint = Config.AMITY_ENDPOINT;
  const apiKey = Config.AMITY_KEY;
  const [fcmToken, setFcmToken] = useState<string | null | undefined>(null);
  const [permissionGranted, setPermissionGranted] = useState(false);
  const { user } = useAuth();

  const registerDevice = useCallback(async (userId: string) => {
    console.log('📤 Registering device');
    const apnsToken = await messaging().getAPNSToken();
    const fcmToken = await messaging().getToken();
    const tokenToSend = Platform.OS === 'ios' ? apnsToken : fcmToken;
    const deviceUuid = await generateUUID();
    const payload = {
      deviceId: deviceUuid,
      platform: Platform.OS,
      userId: userId,
      token: tokenToSend,
    };
    console.log('user?.account.id', user?.account.id);
    console.log('📤 Sending payload:', payload);

    const response = await fetch(`${apiEndpoint}/v1/notification`, {
      method: 'POST',
      headers: {
        'X-API-KEY': apiKey,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });
    console.log('📤 Response:', response);
  }, []);

  useEffect(() => {
    let granted: boolean;
    messaging()
      .hasPermission()
      .then(enabled => {
        granted =
          enabled === messaging.AuthorizationStatus.AUTHORIZED ||
          enabled === messaging.AuthorizationStatus.PROVISIONAL;
        if (!granted) {
          if (Platform.OS === 'android' && Platform.Version > 33) {
            PermissionsAndroid.request('android.permission.POST_NOTIFICATIONS')
              .then(result => {
                granted = result === PermissionsAndroid.RESULTS.GRANTED;
              })
              .finally(() => {
                setPermissionGranted(granted);
              });
          } else {
            messaging()
              .requestPermission()
              .then(result => {
                granted =
                  result === messaging.AuthorizationStatus.AUTHORIZED ||
                  result === messaging.AuthorizationStatus.PROVISIONAL;
              })
              .finally(() => {
                setPermissionGranted(granted);
              });
          }
        }
      })
      .catch(error => console.log(error))
      .finally(() => {
        setPermissionGranted(granted);
      });
    return () => {
      messaging().onTokenRefresh(token => setFcmToken(token));
    };
  }, []);

  useEffect(() => {
    let unsubscribe: () => void;
    if (permissionGranted) {
      messaging()
        .registerDeviceForRemoteMessages()
        .then(() =>
          Platform.select({
            ios: messaging().getAPNSToken(),
            android: messaging().getToken(),
          }),
        )
        .then(async token => {
          setFcmToken(token);
        })
        .catch(error => {
          console.log(error);
        });

      messaging().onNotificationOpenedApp(remoteMessage => {
        console.log(
          'Notification caused app to open from background state:',
          remoteMessage.notification,
        );
      });

      messaging()
        .getInitialNotification()
        .then(remoteMessage => {
          if (remoteMessage) {
            console.log(
              'Notification caused app to open from quit state:',
              remoteMessage.notification,
            );
          }
        });
      unsubscribe = messaging().onMessage(async remoteMessage => {
        console.log(remoteMessage);
      });
    }

    return () => unsubscribe?.();
  }, [permissionGranted]);

  useEffect(() => {
    console.log('📤 useEffect', user?.account.id);
    if (user?.account.id && fcmToken) {
      registerDevice(user.account.id.toString());
    }
  }, [user?.account.id, registerDevice, fcmToken]);
};

Hello @BenGannaway , could you please review and confirm that all items in this checklist have been completed on your end: https://docs.social.plus/technical-faq#what-should-i-do-if-push-notifications-on-ios-are-not-working? Let us know if it’s still not working or if you have any questions.

I’m now getting notifications for activity in the communities. If I post on my own feed though and someone comments/likes I don’t get one. There’s also no section in the portal for switching this on/off. Should I be receiving notifications for user feed activity?

Hello @BenGannaway , Thank you for your question. Currently, notifications for user feed activity (such as receiving comments or likes on your own posts) are not supported. There is also no option in the portal to enable or manage these notifications at this time.

If you have any further questions or feature requests, please let us know!

OK, that seems odd, what’s the reason for that? Is there any plan to implement it?

Also seems like posts sent from the admin panel don’t trigger a notification? or is that a problem at my end?

I’m trying to handle the notifications with Notifee, but the onMessage handler isn’t getting called.

const unsubscribe= messagingInstance.onMessage(asyncremoteMessage => {

Notifications are coming through, but the formatting is not right and the info inside is super basic currently. How can I get this onMessage handler to work with Social Plus notifications?

Hello @BenGannaway , the team is reviewing this at the moment. We’ll keep you updated through our existing email thread.