import httpClient from '@/api/httpClient'; import { registerForPushNotificationsAsync } from '@/components/NotificationProvider'; import { useQueryClient } from '@tanstack/react-query'; import * as Notifications from 'expo-notifications'; import { router } from 'expo-router'; import { useEffect, useRef } from 'react'; import { Platform } from 'react-native'; import { getToken } from './storage.native'; export interface IRegisterDeviceBody { token: string; platform: string; } const commonRequests = { /** * Register device for notification * @param body token * @returns */ async registerDevice(body: IRegisterDeviceBody) { const response = await httpClient.post('https://api.infotarget.uz/api/push-token/', body, { headers: { Authorization: `Bearer ${getToken()}`, }, }); return response; }, }; export function useNotifications() { const notificationListener = useRef(null); const responseListener = useRef(null); const queryClinet = useQueryClient(); useEffect(() => { registerForPushNotificationsAsync().then((token) => { if (!token) return null; const body: IRegisterDeviceBody = { token: token, platform: Platform.OS, }; commonRequests.registerDevice(body); }); notificationListener.current = Notifications.addNotificationReceivedListener( (notification) => {} ); responseListener.current = Notifications.addNotificationResponseReceivedListener((response) => { const data = response.notification.request.content.data; queryClinet.refetchQueries({ queryKey: ['notification-list'] }); queryClinet.refetchQueries({ queryKey: ['notifications-list'] }); if (data?.screen === '/profile/notification') { return; } else { router.push('/profile/notification'); } }); return () => { notificationListener.current?.remove(); responseListener.current?.remove(); }; }, []); }