React Firebase Hooks provides a convenience hook for getting a cloud messaging token, providing an error
and loading
property
to give a complete lifecycle for accessing the cloud messaging token on Firebase Cloud Messaging.
All hooks can be imported from react-firebase-hooks/messaging
, e.g.
import { useToken } from 'react-firebase-hooks/messaging';
List of Cloud Messaging hooks:
const [token, loading, error] = useToken(messaging, vapidKey);
Get a token from Firebase Cloud Messaging
The useToken
hook takes the following parameters:
messaging
:messaging.Messaging
instance for your Firebase appvapidKey
: astring
representing the VAPID key credential needed for Cloud Messaging
Returns:
token
: astring
token to use with cloud messagingloading
: aboolean
to indicate if the function is still being executederror
: AnyError
returned by Firebase when trying to execute the function, orundefined
if there is no error
import { getMessaging } from 'firebase/messaging';
import { useToken } from 'react-firebase-hooks/messaging';
const MessagingToken = () => {
const [token, loading, error] = useToken(getMessaging(firebaseApp));
return (
<div>
<p>
{error && <strong>Error: {JSON.stringify(error)}</strong>}
{loading && <span>Loading token...</span>}
{token && <span>Token:{token}</span>}
</p>
</div>
);
};