Created
March 5, 2022 20:54
-
-
Save KROSF/5a24992829deff02cdbc3f23e88e6af4 to your computer and use it in GitHub Desktop.
Firebase Push Notifications
This file contains 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 messaging, { | |
FirebaseMessagingTypes, | |
} from '@react-native-firebase/messaging'; | |
export const onMessageReceived = async ( | |
message: FirebaseMessagingTypes.RemoteMessage, | |
) => { | |
// handle messages here | |
}; | |
export const setupPushNotifications = () => { | |
messaging().setBackgroundMessageHandler(onMessageReceived); | |
}; |
This file contains 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 messaging from '@react-native-firebase/messaging'; | |
import { requestPushNotificationPermission } from './permission'; | |
import { onMessageReceived } from './handler'; | |
const getFcmToken = async () => { | |
try { | |
const token = await messaging().getToken(); | |
return token; | |
} catch (error) { | |
return undefined; | |
} | |
}; | |
const useForegroundNotificationEffect = () => { | |
useEffect(() => { | |
messaging().onMessage(onMessageReceived); | |
}, []); | |
}; | |
const useFCMTokenEffect = () => { | |
const updateFCMToken = useCallback(async () => { | |
const notificationToken = await getFcmToken(); | |
const hasPermission = await requestPushNotificationPermission(); | |
const saved = { notificationToken: '' }; // Get from your server | |
if (notificationToken === saved.notificationToken || !hasPermission) return; | |
await updateTokenOnYourServer({ notificationToken }); | |
}, []); | |
useEffect(() => { | |
updateFCMToken(); | |
}, [updateFCMToken]); | |
}; | |
const useForegroundNotificationEffect = () => { | |
useEffect(() => { | |
messaging().onMessage(onMessageReceived); | |
}, []); | |
}; | |
export const usePushNotificationEffect = () => { | |
useFCMTokenEffect(); | |
useForegroundNotificationEffect(); | |
}; |
This file contains 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 messaging from '@react-native-firebase/messaging'; | |
export const requestPushNotificationPermission = async () => { | |
try { | |
const status = await messaging().requestPermission(); | |
return ( | |
status === messaging.AuthorizationStatus.AUTHORIZED || | |
status === messaging.AuthorizationStatus.PROVISIONAL | |
); | |
} catch { | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment