Files
info-target-mobile/hooks/useNotifications.ts
Samandar Turgunboyev d747c72c8d complated
2026-02-17 10:46:57 +05:00

71 lines
2.2 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;
}
export 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 queryClient = useQueryClient();
useEffect(() => {
// Android channel
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
// Foreground listener
notificationListener.current = Notifications.addNotificationReceivedListener((notification) => {
console.log('Notification received:', notification);
});
// User response listener
responseListener.current = Notifications.addNotificationResponseReceivedListener((response) => {
const data = response.notification.request.content.data;
queryClient.refetchQueries({ queryKey: ['notification-list'] });
queryClient.refetchQueries({ queryKey: ['notifications-list'] });
router.push('/profile/notification');
});
// Token olish va serverga yuborish
registerForPushNotificationsAsync().then((token) => {
if (!token) return;
commonRequests.registerDevice({ token, platform: Platform.OS });
});
return () => {
notificationListener.current?.remove();
responseListener.current?.remove();
};
}, []);
}