Push notifications with Expo and React Native

I'm developing an App that needs to notify the user, I'm using Expo and React Native to develop Following the Expo documentation I can correctly notify with:

import * as Notifications from 'expo-notifications';
import * as Permissions from 'expo-permissions';
import React, { useState, useEffect } from 'react';
import { Text, View, Button, Platform } from 'react-native';

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

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState('');
  

  useEffect(() => {
    register().then(token => setExpoPushToken(token));
    Notifications.addNotificationReceivedListener()
    Notifications.addNotificationResponseReceivedListener(response => {
      console.log(response);
        });
        

    return () => {
      Notifications.removeAllNotificationListeners();
    };
  }, []);

  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'space-around',
      }}>
     
      
      <Button
        title="Press to Send Notification"
        onPress={async () => {
          await sendPushNotification(expoPushToken);
        }}
      />
    </View>
  );
}



/*
* Envia um evento HTTP para o servidor Expo de notificação-> 
* httpsve://expo.io/dashboard/notifications
*/
async function sendPushNotification(expoPushToken) {
  const message = {
    to: expoPushToken,
    sound: 'default',
    title: 'Voce recebeu uma mensagem',
    body: 'vc tem tinta ferro',
    data: { data: 'goes here' },
  };

  await fetch('https://exp.host/--/api/v2/push/send', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Accept-encoding': 'gzip, deflate',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(message),
  });
}





/**
 * Função para fazer as verificações no dispositivo e retornar o Token de Push
 */
async function register() {
  let token;
  if (Constants.isDevice) {
    const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  return token;
} 

However as I will use in more than one place in the application I do not want to be repeating code so I decided to put in a file the part and adapt it to do the import where I need and pass as a parameter only title and Body , with this arrive at the following code:

import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';
import * as Permissions from 'expo-permissions';
import React, { useState, useEffect } from 'react';
import { Text, View, Button, Platform } from 'react-native';



export default function App() {

    Notifications.setNotificationHandler({
        handleNotification: async () => ({
            shouldShowAlert: true,
            shouldPlaySound: true,
            shouldSetBadge: true,
        }),
    });
    
    const [expoPushToken, setExpoPushToken] = useState('');
    

    /**
 * Função para fazer as verificações no dispositivo e retornar o Token de Push
 */
    async function register() {
        let token;
        if (Constants.isDevice) {
            const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
            let finalStatus = existingStatus;
            if (existingStatus !== 'granted') {
                const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
                finalStatus = status;
            }
            if (finalStatus !== 'granted') {
                alert('Failed to get push token for push notification!');
                return;
            }
            token = (await Notifications.getExpoPushTokenAsync()).data;
            console.log(token);
            setExpoPushToken(token)
        } else {
            alert('Must use physical device for Push Notifications');
        }

        if (Platform.OS === 'android') {
            Notifications.setNotificationChannelAsync('default', {
                name: 'default',
                importance: Notifications.AndroidImportance.MAX,
                vibrationPattern: [0, 250, 250, 250],
                lightColor: '#FF231F7C',
            });
        }
    }
    

    /*
    * Envia um evento HTTP para o servidor Expo de notificação-> 
    * httpsve://expo.io/dashboard/notifications
    */
    async function sendPushNotification() {
        const message = {
            to: expoPushToken,
            sound: 'default',
            title: "teste",
            body: "ETTETETETET",
            data: { data: 'goes here' },
        };

        await fetch('https://exp.host/--/api/v2/push/send', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Accept-encoding': 'gzip, deflate',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(message),
        });
    }

    register().then(response => console.log("Correto"))

    sendPushNotification().then(resoponse => console.log("Correto"))

  
}

And I call it in my index as follows:


import React from 'react';
import { StyleSheet, Button, View } from 'react-native';
import Appl from './notification'

export default function App() {
  

  return (
  
  <View style={{
    marginTop: 100,
  }}>
    <Button  title="Notificar" onPress={Appl()} />
  </View>
  
  
    
  );
}

Of course I've tried other ways but none works.

Author: Geovane, 2020-07-14

1 answers

Where is the token in the function? Isn't he going through?

Where has expoPushToken has to be the push token.

 async function sendPushNotification( expoPushToken ) {
        const message = {
            to: expoPushToken,
            sound: 'default',
            title: "teste",
            body: "ETTETETETET",
            data: { data: 'goes here' },
        };
 0
Author: paulocr111, 2020-12-13 19:26:05