Files
info-target-mobile/hooks/useNotifications.ts
Samandar Turgunboyev a7419929f8 complated project
2026-02-02 18:51:53 +05:00

67 lines
1.9 KiB
TypeScript

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<any>(null);
const responseListener = useRef<any>(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();
};
}, []);
}