Cours React Native · Module 7: Notifications

Notifications push

2 min de lecture ·
Dans cette leçon4

Les notifications push sont envoyées depuis un serveur vers l'appareil de l'utilisateur.

Expo Push Service

// Côté serveur (Node.js)
import { Expo, ExpoPushMessage } from 'expo-server-sdk';

const expo = new Expo();

async function sendPushNotification(pushToken: string, title: string, body: string) {
  const message: ExpoPushMessage = {
    to: pushToken,
    sound: 'default',
    title,
    body,
    data: { someData: 'goes here' },
  };

  const chunks = expo.chunkPushNotifications([message]);
  const tickets = [];

  for (const chunk of chunks) {
    const ticketChunk = await expo.sendPushNotificationsAsync(chunk);
    tickets.push(...ticketChunk);
  }

  return tickets;
}

Envoi avec curl (test)

curl -H "Content-Type: application/json" -X POST \
  "https://exp.host/--/api/v2/push/send" \
  -d '{
    "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
    "title":"Message de l'Atlantide",
    "body": "Poséidon t'appelle !"
  }'

Stocker le token sur le serveur

// Dans l'app - après l'inscription de l'utilisateur
async function savePushToken() {
  const token = await registerForPushNotificationsAsync();

  if (token) {
    // Envoyer le token à ton serveur
    await fetch('https://api.atlantis.app/users/push-token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        token: token.data,
        platform: Platform.OS,
      }),
    });
  }
}

Gérer les notifications reçues

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

function useNotifications() {
  const notificationListener = useRef<Notifications.Subscription>();
  const responseListener = useRef<Notifications.Subscription>();

  useEffect(() => {
    // Listener pour la notification reçue (app au premier plan)
    notificationListener.current = Notifications.addNotificationReceivedListener(
      (notification) => {
        console.log('Reçue :', notification);
      }
    );

    // Listener pour l'interaction avec la notification
    responseListener.current = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        const data = response.notification.request.content.data;
        console.log('Notification touchée :', data);

        // Naviguer en fonction des données
        if (data.screen) {
          navigation.navigate(data.screen, data);
        }
      }
    );

    return () => {
      notificationListener.current?.remove();
      responseListener.current?.remove();
    };
  }, []);
}

Les notifications push permettent de communiquer avec l'utilisateur même quand l'app est fermée !

Code de cette leçon : App.tsx
import { useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as Notifications from 'expo-notifications';

// Hook gérant la réception et le tap sur une notification
function useNotifications() {
  const [lastNotification, setLastNotification] = useState<string>('');
  const notificationListener = useRef<Notifications.Subscription>();
  const responseListener = useRef<Notifications.Subscription>();

  useEffect(() => {
    // TODO : listener pour une notification reçue (application au premier plan)
    // utilise Notifications.addNotificationReceivedListener
    notificationListener.current = Notifications.addNotificationReceivedListener(
      (notification) => {
        // TODO : enregistre le titre de la notification dans le state
        setLastNotification('');
      }
    );

    // TODO : listener pour le tap/l'interaction avec la notification
    // utilise Notifications.addNotificationResponseReceivedListener
    responseListener.current = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        const data = response.notification.request.content.data;
        console.log('Tapped:', data);
      }
    );

    // TODO : nettoie les abonnements dans la fonction de nettoyage (remove())
    return () => {
      notificationListener.current?.remove();
      responseListener.current?.remove();
    };
  }, []);

  return { lastNotification };
}

export default function App() {
  const { lastNotification } = useNotifications();

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Notifications Push</Text>
      <Text style={styles.info}>Dernière : {lastNotification || 'aucune'}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#1a5276' },
  title: { fontSize: 24, color: '#fff', marginBottom: 12 },
  info: { fontSize: 14, color: '#aed6f1' },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Quel format a l'Expo Push Token ?

  2. 2. Vers quelle URL envoie-t-on les push via Expo ?

Voici 2 des 4 questions de cette leçon. Réponds aux autres dans le jeu.

Tâches pratiques dans le jeu

  • Tri vertical

    Ordonne le payload de la notification push :

  • Éditeur de code

    Complète le code avec les listeners.

Articles utiles