|
| 1 | +# React Firebase Hooks - Cloud Messaging |
| 2 | + |
| 3 | +React Firebase Hooks provides a convenience hook for getting a cloud messaging token, providing an `error` and `loading` property |
| 4 | +to give a complete lifecycle for accessing the cloud messaging token on Firebase Cloud Messaging. |
| 5 | + |
| 6 | +All hooks can be imported from `react-firebase-hooks/messaging`, e.g. |
| 7 | + |
| 8 | +```js |
| 9 | +import { useToken } from 'react-firebase-hooks/messaging'; |
| 10 | +``` |
| 11 | + |
| 12 | +List of Cloud Messaging hooks: |
| 13 | + |
| 14 | +- [React Firebase Hooks - Cloud Messaging](#react-firebase-hooks---cloud-messaging) |
| 15 | + - [useToken](#usetoken) |
| 16 | + - [Full example](#full-example) |
| 17 | + |
| 18 | +### useToken |
| 19 | + |
| 20 | +```js |
| 21 | +const [token, loading, error] = useToken(messaging); |
| 22 | +``` |
| 23 | + |
| 24 | +Get a token from Firebase Cloud Messaging |
| 25 | + |
| 26 | +The `useToken` hook takes the following parameters: |
| 27 | + |
| 28 | +- `messaging`: `messaging.Messaging` instance for your Firebase app |
| 29 | + |
| 30 | +Returns: |
| 31 | + |
| 32 | +- `token`: a `string` token to use with cloud messaging |
| 33 | +- `loading`: a `boolean` to indicate if the function is still being executed |
| 34 | +- `error`: Any `Error` returned by Firebase when trying to execute the function, or `undefined` if there is no error |
| 35 | + |
| 36 | +#### Full example |
| 37 | + |
| 38 | +```js |
| 39 | +import { getMessaging } from 'firebase/messaging'; |
| 40 | +import { useToken } from 'react-firebase-hooks/messaging'; |
| 41 | + |
| 42 | +const MessagingToken = () => { |
| 43 | + const [token, loading, error] = useToken(getMessaging(firebaseApp)); |
| 44 | + return ( |
| 45 | + <div> |
| 46 | + <p> |
| 47 | + {error && <strong>Error: {JSON.stringify(error)}</strong>} |
| 48 | + {loading && <span>Loading token...</span>} |
| 49 | + {token && <span>Token:{token}</span>} |
| 50 | + </p> |
| 51 | + </div> |
| 52 | + ); |
| 53 | +}; |
| 54 | +``` |
0 commit comments