summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2024-10-28 08:55:24 +0100
committerSanto Cariotti <santo@dcariotti.me>2024-10-28 08:55:24 +0100
commit038be5daf65c3408304b3d7fbdb4c4003cfd1b6a (patch)
tree9de73d5de0940bf8e005a54afa8dc4d45c7902d6
parent0c5181056d0977bbb63e34df941a3665a65a50b4 (diff)
Fetch noitification with a push handler
-rw-r--r--app/(tabs)/index.tsx78
-rw-r--r--components/ParallaxScrollView.tsx69
2 files changed, 77 insertions, 70 deletions
diff --git a/app/(tabs)/index.tsx b/app/(tabs)/index.tsx
index da967c7..9fff8f8 100644
--- a/app/(tabs)/index.tsx
+++ b/app/(tabs)/index.tsx
@@ -10,14 +10,14 @@ import {
import ParallaxScrollView from "@/components/ParallaxScrollView";
import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
-import React, { useState, useEffect, useRef } from "react";
+import React, { useState, useEffect, useRef, useCallback } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import MapView, { LatLng, Marker } from "react-native-maps";
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
import * as Location from "expo-location";
import Constants from "expo-constants";
-import { Link } from "expo-router";
+import { Link, useFocusEffect } from "expo-router";
import * as TaskManager from "expo-task-manager";
import { Audio } from 'expo-av';
@@ -370,53 +370,55 @@ export default function HomeScreen() {
} catch (err) {
console.error("Error on updating position");
}
-
}
- 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, level, alert { id, text1 text2 text3 }, movingActivity } }`,
- }),
+ 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, level, alert { id, text1 text2 text3 }, movingActivity } }`,
+ }),
+ },
+ );
- const data = await response.json();
+ const data = await response.json();
- if (data.data && data.data.notifications && data.data.notifications.length) {
- const n = data.data.notifications[0];
- setNotification(notification);
- if (n.position.movingActivity == "IN_VEHICLE") {
- playSound(n.alert.id, n.level);
- }
- } else {
- setNotification(null);
+ if (data.data && data.data.notifications && data.data.notifications.length) {
+ const n = data.data.notifications[0];
+ setNotification(n);
+ if (n.movingActivity == "IN_VEHICLE") {
+ playSound(n.alert.id, n.level);
}
- } catch (err) {
- console.error("Fetch notifications:", err);
+ } else {
+ setNotification(null);
}
- };
-
- if (token && userId) {
- const intervalId = setInterval(fetchNotifications, 10000);
-
- return () => clearInterval(intervalId);
- } else {
- setNotification(null);
+ } catch (err) {
+ console.error("Fetch notifications:", err);
}
+ };
+
+ useEffect(() => {
+ Notifications.addNotificationReceivedListener(() => {
+ fetchNotifications();
+ });
}, [token, userId]);
+ useFocusEffect(useCallback(() => {
+ fetchNotifications();
+ }, []))
+
useEffect(() => {
const retrieveToken = async () => {
const storedToken =
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={{