Added saving of push notifications
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user