From 038be5daf65c3408304b3d7fbdb4c4003cfd1b6a Mon Sep 17 00:00:00 2001
From: Santo Cariotti <santo@dcariotti.me>
Date: Mon, 28 Oct 2024 08:55:24 +0100
Subject: Fetch noitification with a push handler

---
 components/ParallaxScrollView.tsx | 69 +++++++++++++++++++++------------------
 1 file changed, 37 insertions(+), 32 deletions(-)

(limited to 'components')

diff --git a/components/ParallaxScrollView.tsx b/components/ParallaxScrollView.tsx
index 3772bee..30df3c0 100644
--- a/components/ParallaxScrollView.tsx
+++ b/components/ParallaxScrollView.tsx
@@ -1,10 +1,11 @@
-import { useState, type PropsWithChildren, useEffect, } from 'react';
+import { useState, type PropsWithChildren, useEffect, useCallback, } from 'react';
 import { StyleSheet, SafeAreaView, useColorScheme, View, Text, Pressable, Platform } from 'react-native';
 
+import * as Notifications from "expo-notifications";
 import { ThemedView } from '@/components/ThemedView';
 import { ThemedText } from './ThemedText';
 import { Ionicons } from '@expo/vector-icons';
-import { router } from 'expo-router';
+import { router, useFocusEffect } from 'expo-router';
 
 
 type Props = PropsWithChildren<{
@@ -22,44 +23,48 @@ export default function ParallaxScrollView({
   const theme = useColorScheme() ?? 'light';
   const [notifications, setNotifications] = useState([]);
 
-  useEffect(() => {
-    const fetchNotifications = async () => {
-      if (!token || !userId) return;
+  /**
+   * Fetch notifications from the server for a given user.
+   */
+  const fetchNotifications = async () => {
+    if (!token || !userId) return;
 
-      try {
-        const response = await fetch(
-          `${process.env.EXPO_PUBLIC_API_URL}/graphql`,
-          {
-            method: 'POST',
-            headers: {
-              Authorization: `Bearer ${token}`,
-              'Content-Type': 'application/json',
-            },
-            body: JSON.stringify({
-              query: `{ notifications(seen: false) { id, createdAt } }`,
-            }),
-          }
-        );
+    try {
+      const response = await fetch(
+        `${process.env.EXPO_PUBLIC_API_URL}/graphql`,
+        {
+          method: 'POST',
+          headers: {
+            Authorization: `Bearer ${token}`,
+            'Content-Type': 'application/json',
+          },
+          body: JSON.stringify({
+            query: `{ notifications(seen: false) { id, createdAt } }`,
+          }),
+        }
+      );
 
-        const data = await response.json();
+      const data = await response.json();
 
-        if (data.data.notifications) {
-          setNotifications(data.data.notifications);
-        }
-      } catch (err) {
-        console.error('Fetch notifications:', err);
+      if (data.data.notifications) {
+        setNotifications(data.data.notifications);
       }
-    };
+    } catch (err) {
+      console.error('Fetch notifications:', err);
+    }
+  };
 
-    if (token && userId) {
-      const intervalId = setInterval(fetchNotifications, 2000);
 
-      return () => clearInterval(intervalId);
-    } else {
-      setNotifications([]);
-    }
+  useEffect(() => {
+    Notifications.addNotificationReceivedListener(() => {
+      fetchNotifications();
+    });
   }, [token, userId]);
 
+  useFocusEffect(useCallback(() => {
+    fetchNotifications();
+  }, []))
+
   return (
     <ThemedView style={styles.container}>
       <SafeAreaView style={{
-- 
cgit v1.2.3-18-g5258