frontend-app/hooks/usePushNotifications.ts
2025-09-30 18:12:04 +02:00

74 lines
1.7 KiB
TypeScript

import * as Notifications from "expo-notifications";
import * as Permissions from "expo-permissions";
import { useEffect, useState } from "react";
import { Platform } from "react-native";
type RegisterTokenParams = {
userId: number;
apiKey: string;
backendUrl: string;
appVersion?: string;
locale?: string;
topics?: string[];
};
export function usePushNotifications({
userId,
apiKey,
backendUrl,
appVersion = "1.0.0",
locale,
topics
}: RegisterTokenParams) {
const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
useEffect(() => {
(async () => {
const token = await registerForPushNotificationsAsync();
if (token) {
setExpoPushToken(token);
await registerTokenWithBackend(token);
}
})();
}, []);
const registerTokenWithBackend = async (token: string) => {
try {
await fetch(`${backendUrl}/register_token`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": apiKey
},
body: JSON.stringify({
user_id: userId,
token,
platform: Platform.OS,
app_ver: appVersion,
locale,
topics
})
});
console.log("Push token registered with backend ✅");
} catch (error) {
console.error("Failed to register token with backend:", error);
}
};
return expoPushToken;
}
async function registerForPushNotificationsAsync() {
let { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
if (status !== "granted") {
console.log("Permission not granted for push notifications.");
return null;
}
const tokenData = await Notifications.getExpoPushTokenAsync();
const token = tokenData.data;
console.log("Expo Push Token:", token);
return token;
}