Last active
May 26, 2020 12:59
-
-
Save lucasfloriani/efe63e3b5b4aee57ffe66dc043c27515 to your computer and use it in GitHub Desktop.
useFirebase hook
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 React from 'react' | |
| import useFirebaseMessaging from '@hooks/useFirebase' | |
| const HowToUse = () => { | |
| useFirebaseMessaging() | |
| return <p>Firebase Messaging executed</p> | |
| } |
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 { useEffect, useRef } from 'react' | |
| import firebase from 'firebase/app' | |
| import 'firebase/messaging' | |
| import firebaseConfig from '@services/firebaseConfig' | |
| import { useDispatch } from 'react-redux' | |
| import { Creators as AlertActions } from '@store/ducks/alert' | |
| import { Creators as FirebaseActions } from '@store/ducks/firebase' | |
| const useFirebaseMessaging = () => { | |
| const dispatch = useDispatch() | |
| const onMessageUnsubscribe = useRef(null) | |
| const onTokenRefreshUnsubscribe = useRef(null) | |
| useEffect(() => { | |
| const firebaseMessaging = async () => { | |
| if (!firebase.messaging.isSupported()) return | |
| if (!firebase.apps.length) firebase.initializeApp(firebaseConfig) | |
| const messaging = firebase.messaging() | |
| onMessageUnsubscribe.current = messaging.onMessage((payload) => { | |
| const message = payload.notification.body | |
| const { redirectUrl } = payload.data | |
| dispatch(AlertActions.createAlertByPushNotification(message, redirectUrl)) | |
| }) | |
| const registerUserDevice = async () => { | |
| const token = await messaging.getToken() | |
| dispatch(FirebaseActions.registerPushNotificationUserRequest(token)) | |
| } | |
| onTokenRefreshUnsubscribe.current = messaging.onTokenRefresh(registerUserDevice) | |
| try { | |
| await messaging.requestPermission() | |
| await registerUserDevice() | |
| } catch (err) { | |
| if (err.code !== 'messaging/permission-blocked') return | |
| const errorMessageOnRegister = 'Não foi possível cadastrar seu dispositivo para receber push notifications' | |
| dispatch(AlertActions.createErrorAlert(errorMessageOnRegister)) | |
| } | |
| } | |
| firebaseMessaging() | |
| return () => { | |
| if (onTokenRefreshUnsubscribe.current) onTokenRefreshUnsubscribe.current() | |
| if (onMessageUnsubscribe.current) onMessageUnsubscribe.current() | |
| } | |
| }, [dispatch]) | |
| } | |
| export default useFirebaseMessaging |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment