Created
January 10, 2023 09:19
-
-
Save Meetcpatel/0a81cd03df6854beeeca0b3310b7a126 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useLazyQuery } from "@apollo/client"; | |
import { useEffect, useRef, useState } from "react"; | |
import { Alert, Platform, } from "react-native" | |
import * as Device from 'expo-device'; | |
import * as Notifications from 'expo-notifications'; | |
import { GET_USER } from "../component/GraphQL/Queries"; | |
Notifications.setNotificationHandler({ | |
handleNotification: async () => ({ | |
shouldShowAlert: true, | |
shouldPlaySound: false, | |
shouldSetBadge: false, | |
}), | |
}); | |
export const Notification = () => { | |
const [user, SetUser] = useState<any>(); | |
const [getUserDetail, { data, error }] = useLazyQuery(GET_USER, { | |
variables: { email: user }, | |
}); | |
const [expoPushToken, setExpoPushToken] = useState(''); | |
const [notification, setNotification] = useState<any | boolean>(false); | |
const notificationListener = useRef<any>(); | |
const responseListener = useRef<any>(); | |
async function registerForPushNotificationsAsync() { | |
let token; | |
if (Device.isDevice) { | |
const { status: existingStatus } = await Notifications.getPermissionsAsync(); | |
let finalStatus = existingStatus; | |
if (existingStatus !== 'granted') { | |
const { status } = await Notifications.requestPermissionsAsync(); | |
finalStatus = status; | |
} | |
if (finalStatus !== 'granted') { | |
alert('Failed to get push token for push notification!'); | |
return; | |
} | |
token = (await Notifications.getExpoPushTokenAsync()).data; | |
console.log(token); | |
} else { | |
alert('Must use physical device for Push Notifications'); | |
} | |
if (Platform.OS === 'android') { | |
Notifications.setNotificationChannelAsync('default', { | |
name: 'default', | |
importance: Notifications.AndroidImportance.MAX, | |
vibrationPattern: [0, 250, 250, 250], | |
lightColor: '#FF231F7C', | |
}); | |
} | |
return token; | |
} | |
async function sendPushNotification(expoPushToken: any) { | |
if (!expoPushToken) return; | |
const message = { | |
to: expoPushToken, | |
sound: 'default', | |
title: 'Original Title', | |
body: 'And here is the body!', | |
data: { someData: 'goes here' }, | |
}; | |
try { | |
await fetch('https://exp.host/--/api/v2/push/send', { | |
method: 'POST', | |
headers: { | |
Accept: 'application/json', | |
'Accept-encoding': 'gzip, deflate', | |
'Content-Type': 'application/json', | |
}, | |
body: JSON.stringify(message), | |
}); | |
Alert.alert("Notification sent") | |
SetUser(''); | |
} catch (error) { | |
Alert.alert("Somthing went wrong while sending notification") | |
} | |
} | |
const getUserTokenAndSendNotification = async (userEmail: any) => { | |
if (!userEmail) return; | |
SetUser(userEmail) | |
} | |
useEffect(() => { | |
if (data) { | |
if (data?.user?.token) { | |
sendPushNotification(data?.user?.token) | |
} | |
} | |
if (error) { | |
console.log("error", error) | |
} | |
}, [data, error]) | |
useEffect(() => { | |
getUserDetail() | |
}, [user]) | |
useEffect(() => { | |
registerForPushNotificationsAsync().then((token: any) => setExpoPushToken(token)); | |
// This listener is fired whenever a notification is received while the app is foregrounded | |
notificationListener.current = Notifications.addNotificationReceivedListener((notification: any) => { | |
setNotification(notification); | |
}); | |
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed) | |
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => { | |
console.log(response); | |
}); | |
return () => { | |
Notifications.removeNotificationSubscription(notificationListener.current); | |
Notifications.removeNotificationSubscription(responseListener.current); | |
}; | |
}, []); | |
return { getUserTokenAndSendNotification } | |
} | |
// How to send notification ? | |
// import below things in component | |
// import { Notification } from "./Notification"; | |
// inside function component use hook | |
// const { getUserTokenAndSendNotification } = Notification(); | |
// and call getUserTokenAndSendNotification with useremail | |
// getUserTokenAndSendNotification('[email protected]'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment