UNPKG

react-firebase-hooks

Version:
80 lines (72 loc) 3.33 kB
import { getToken } from 'firebase/messaging'; import { useMemo, useReducer, useCallback, useEffect } from 'react'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var defaultState = function (defaultValue) { return { loading: defaultValue === undefined || defaultValue === null, value: defaultValue, }; }; var reducer = function () { return function (state, action) { switch (action.type) { case 'error': return __assign(__assign({}, state), { error: action.error, loading: false, value: undefined }); case 'reset': return defaultState(action.defaultValue); case 'value': return __assign(__assign({}, state), { error: undefined, loading: false, value: action.value }); default: return state; } }; }; var useLoadingValue = (function (getDefaultValue) { var defaultValue = getDefaultValue ? getDefaultValue() : undefined; var _a = useReducer(reducer(), defaultState(defaultValue)), state = _a[0], dispatch = _a[1]; var reset = useCallback(function () { var defaultValue = getDefaultValue ? getDefaultValue() : undefined; dispatch({ type: 'reset', defaultValue: defaultValue }); }, [getDefaultValue]); var setError = useCallback(function (error) { dispatch({ type: 'error', error: error }); }, []); var setValue = useCallback(function (value) { dispatch({ type: 'value', value: value }); }, []); return useMemo(function () { return ({ error: state.error, loading: state.loading, reset: reset, setError: setError, setValue: setValue, value: state.value, }); }, [state.error, state.loading, reset, setError, setValue, state.value]); }); var useToken = (function (messaging, vapidKey) { var _a = useLoadingValue(), error = _a.error, loading = _a.loading, setError = _a.setError, setValue = _a.setValue, value = _a.value; useEffect(function () { getToken(messaging, { vapidKey: vapidKey }).then(setValue).catch(setError); }, [messaging]); return [value, loading, error]; }); export { useToken };