1. Nós no dia anterior criamos o hábito, porém sem notificação de fato, vamos fazer isso hoje. Nós vamos colocar a notificação no nosso app.

  2. Para usarmos notificação, nós temos vários códigos padrão para pegar, que vem da documentação ⇒ https://docs.expo.dev/versions/latest/sdk/notifications/ (Mostrar ela em vídeo, mais precisamente na parte de “API”, que é a parte do link)

  3. Antes, nós vamos instalar o expo-notifications.

    npx expo install expo-notifications
    
    npx expo install react-native-screens react-native-safe-area-context
    
  4. Agora que temos a biblioteca instalada podemos começar a utilizá-la para mostrar as notificações. Vamos importar as notificações na página HabitPage

“Pages → HabitPage → index.jsx”

import React, { useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Alert,
  ScrollView,
} from "react-native";
import * as Notifications from "expo-notifications";

import { useNavigation } from "@react-navigation/native";

import SelectHabit from "../../Components/HabitPage/SelectHabit";
import SelectFrequency from "../../Components/HabitPage/SelectFrequency";
import Notification from "../../Components/HabitPage/Notification";
import TimeDatePicker from "../../Components/HabitPage/TimeDataPicker";
import UpdateExcludeButtons from "../../Components/HabitPage/UpdateExcludeButtons";
import DefaultButton from "../../Components/Common/DefaultButton";

import HabitsService from "../../services/HabitsService";

export default function HabitPage({ route }) {
  1. Agora, nós iremos copiar um dos passos que vai fazer a “setagem” da notificação

    import React, { useState } from "react";
    import {
      View,
      Text,
      StyleSheet,
      Image,
      TouchableOpacity,
      Alert,
      ScrollView,
    } from "react-native";
    
    import * as Notifications from "expo-notifications";
    
    import { useNavigation } from "@react-navigation/native";
    
    import SelectHabit from "../../Components/HabitPage/SelectHabit";
    import SelectFrequency from "../../Components/HabitPage/SelectFrequency";
    import Notification from "../../Components/HabitPage/Notification";
    import TimeDatePicker from "../../Components/HabitPage/TimeDataPicker";
    import UpdateExcludeButtons from "../../Components/HabitPage/UpdateExcludeButtons";
    import DefaultButton from "../../Components/Common/DefaultButton";
    
    import HabitsService from "../../services/HabitsService";
    
    Notifications.setNotificationHandler({
      handleNotification: async () => ({
        shouldShowAlert: true,
        shouldPlaySound: false,
        shouldSetBadge: false,
      }),
    });
    
    export default function HabitPage({ route }) {
    
  2. Agora, nós iremos adicionar estados que vão fazer modificações na notificação. (Caso queira, pode deixar o comentário para separar)

    import React, { useEffect, useRef, useState } from "react";
    
    // ... Outros códigos
    
    export default function HabitPage({ route }) {
    const navigation = useNavigation();
    const [habitInput, setHabitInput] = useState();
    const [frequencyInput, setFrequencyInput] = useState();
    const [notificationToggle, setNotificationToggle] = useState();
    const [dayNotification, setDayNotification] = useState();
    const [timeNotification, setTimeNotification] = useState();
    
    const habitCreated = new Date();
    const formatDate = `${habitCreated.getFullYear()}-${
      habitCreated.getMonth() + 1
    }-${habitCreated.getDate()}`;
    
    // Notification Creation
    const [notification, setNotification] = useState(false);
    const notificationListener = useRef();
    const responseListener = useRef();
    
    // ... Outros códigos
    
  3. Nós vamos agora adicionar dois useEffect, que ficarão responsáveis pela verificação de notificação. Ou seja, se ele estiver ativo, vamos tomar algumas decisões, caso não esteja, vamos tomar outras.

a) O primeiro recebe os parametros de rota da Habit Page, verifica se tem a notificação ativa e seta o ToggleNotification como true, seta a frequencia, data e hora da notificação.

b) Quando atualizar o switch ele vai fazer uma verificação, se for falso, ele limpa os states da notificação.

Obs.: é importante que esses useEffect() sejam colocados abaixo da definição dos parâmetros de rota.

// ... Outros códigos

function handleUpdateHabit() {
  if (notificationToggle === true && !dayNotification && !timeNotification) {
    Alert.alert("Você precisa colocar a frequência e horário da notificação");
  } else {
    HabitsService.updateHabit({
      habitArea: habitArea,
      habitName: habitInput,
      habitFrequency: frequencyInput,
      habitHasNotification: notificationToggle,
      habitNotificationFrequency: dayNotification,
      habitNotificationTime: timeNotification,
      habitNotificationId: notificationToggle ? habitInput : null,
    }).then(() => {
      Alert.alert("Sucesso na atualização do hábito");
      if (!notificationToggle) {
        NotificationService.deleteNotification(habitInput);
      } else {
        NotificationService.createNotification(
          habitInput,
          frequencyInput,
          dayNotification,
          timeNotification
        );
      }
      navigation.navigate("Home", {
        updatedHabit: `Updated in ${habitArea}`,
      });
    });
  }
}

useEffect(() => {
  if (habit?.habitHasNotification == 1) {
    setNotificationToggle(true);
    setDayNotification(habit?.habitNotificationFrequency);
    setTimeNotification(habit?.habitNotificationTime);
  }
}, []);

useEffect(() => {
  if (notificationToggle === false) {
    setTimeNotification(null);
    setDayNotification(null);
  }
}, [notificationToggle]);

// ... Outros códigos
  1. E por fim, abaixo dos useEffect que acabamos de criar, teremos mais um, que vem da doc também.

    Obs.: nesse caso também é importante que usemos o return do useEffect() para fazer a limpeza dos listeners.

    // ... Outros códigos
    
    useEffect(() => {
      if (habit?.habitHasNotification == 1) {
        setNotificationToggle(true);
        setDayNotification(habit?.habitNotificationFrequency);
        setTimeNotification(habit?.habitNotificationTime);
      }
    }, []);
    
    useEffect(() => {
      if (notificationToggle === false) {
        setTimeNotification(null);
        setDayNotification(null);
      }
    }, [notificationToggle]);
    
    // Notification Get Token
    useEffect(() => {
      notificationListener.current = Notifications.addNotificationReceivedListener((notification) => {
        setNotification(notification);
      });
    
      responseListener.current = Notifications.addNotificationResponseReceivedListener((response) => {
        console.log(response);
      });
    
      return () => {
        Notifications.removeNotificationSubscription(notificationListener.current);
        Notifications.removeNotificationSubscription(responseListener.current);
      };
    }, []);
    
    // ... Outros códigos