tooot/src/utils/push/useReceive.ts

48 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-03-02 01:17:06 +01:00
import { displayMessage } from '@components/Message'
2022-01-30 22:51:03 +01:00
import queryClient from '@helpers/queryClient'
import initQuery from '@utils/initQuery'
2021-03-02 01:17:06 +01:00
import { QueryKeyTimeline } from '@utils/queryHooks/timeline'
import { getInstances } from '@utils/slices/instancesSlice'
2021-03-02 01:17:06 +01:00
import * as Notifications from 'expo-notifications'
import { useEffect } from 'react'
import { useSelector } from 'react-redux'
2021-03-04 01:03:53 +01:00
import pushUseNavigate from './useNavigate'
2021-03-02 01:17:06 +01:00
const pushUseReceive = () => {
const instances = useSelector(getInstances, (prev, next) => prev.length === next.length)
2021-03-02 01:17:06 +01:00
useEffect(() => {
const subscription = Notifications.addNotificationReceivedListener(notification => {
const queryKey: QueryKeyTimeline = ['Timeline', { page: 'Notifications' }]
queryClient.invalidateQueries(queryKey)
const payloadData = notification.request.content.data as {
notification_id?: string
instanceUrl: string
accountId: string
}
2021-03-02 01:17:06 +01:00
const notificationIndex = instances.findIndex(
instance =>
instance.url === payloadData.instanceUrl && instance.account.id === payloadData.accountId
)
displayMessage({
duration: 'long',
message: notification.request.content.title!,
description: notification.request.content.body!,
onPress: () => {
if (notificationIndex !== -1) {
initQuery({
instance: instances[notificationIndex],
prefetch: { enabled: true }
})
2021-03-02 01:17:06 +01:00
}
pushUseNavigate(payloadData.notification_id)
}
})
})
2021-03-02 01:17:06 +01:00
return () => subscription.remove()
}, [instances])
}
2021-03-04 01:03:53 +01:00
export default pushUseReceive