Added saving of push notifications

This commit is contained in:
2025-10-03 10:23:56 +02:00
parent cd5c6a87b5
commit f8bfd9f218
4 changed files with 793 additions and 735 deletions

View File

@@ -1,25 +1,44 @@
import * as Notifications from "expo-notifications";
import { useEffect } from "react";
import { Item } from "types/Item";
export function useNotificationListener(
onNotificationReceived: (notification: Notifications.Notification) => void
) {
// Hook to listen for incoming notifications and map them into Item objects
export function useNotificationListener(onItem: (item: Item) => void) {
useEffect(() => {
// Listener for notifications received while app is in foreground
const subscription = Notifications.addNotificationReceivedListener(notification => {
console.log("Notification received:", notification);
onNotificationReceived(notification);
// Listen for notification received while app is in foreground
const receivedSub = Notifications.addNotificationReceivedListener((notification) => {
const item = mapNotificationToItem(notification);
if (item) onItem(item);
});
// Listener for user interacting with a notification
const responseSubscription = Notifications.addNotificationResponseReceivedListener(response => {
console.log("Notification response:", response);
onNotificationReceived(response.notification);
// Listen for when user taps a notification
const responseSub = Notifications.addNotificationResponseReceivedListener((response) => {
const item = mapNotificationToItem(response.notification);
if (item) onItem(item);
});
// Cleanup on unmount
return () => {
subscription.remove();
responseSubscription.remove();
receivedSub.remove();
responseSub.remove();
};
}, []);
}, [onItem]);
}
// Helper: convert Expo notification → Item
function mapNotificationToItem(notification: Notifications.Notification): Item | null {
try {
const content = notification.request.content;
return {
timestamp: Date.now(), // Or use content.data.timestamp if backend includes it
category: (content.data?.category as Item["category"]) ?? "home",
title: content.title ?? "No title",
info: content.body ?? "No details",
link: (content.data?.link as string) ?? "",
};
} catch (e) {
console.error("Failed to map notification to Item:", e);
return null;
}
}