Push notifications with Expo and React Native

Asked

Viewed 1,136 times

0

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 keep repeating code so I decided to put in a file and adapt it to do the Import where you need it and pass as parameter only Title and Body, with that thought reach 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 him on 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.

1 answer

0

Where’s the function token? He’s not passing by?

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' },
        };

Browser other questions tagged

You are not signed in. Login or sign up in order to post.