UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

51 lines (50 loc) 2.21 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var createHandlerSetter_1 = __importDefault(require("./factory/createHandlerSetter")); var geolocationUtils_1 = require("./shared/geolocationUtils"); /** * Returns a frozen object of callback setters to handle the geolocation events.<br/> * So far, the supported methods are: `onChange`, invoked when the position changes and `onError`, invoked when * an error occur while retrieving the position.<br/> * The returned object also contains the `isSupported` boolean flag reporting whether the geolocation API is supported. */ var useGeolocationEvents = function (options) { if (options === void 0) { options = geolocationUtils_1.geoStandardOptions; } var watchId = (0, react_1.useRef)(); var _a = (0, createHandlerSetter_1.default)(), onChangeRef = _a[0], setOnChangeRef = _a[1]; var _b = (0, createHandlerSetter_1.default)(), onErrorRef = _b[0], setOnErrorRef = _b[1]; var isSupported = (0, react_1.useMemo)(function () { return typeof window !== 'undefined' && 'geolocation' in window.navigator; }, []); if (!isSupported) { throw new Error('The Geolocation API is not supported'); } (0, react_1.useEffect)(function () { var onSuccess = function (successEvent) { if (onChangeRef.current) { onChangeRef.current(successEvent); } }; var onError = function (err) { if (onErrorRef.current) { onErrorRef.current(err); } }; if (isSupported) { watchId.current = window.navigator.geolocation.watchPosition(onSuccess, onError, options); } return function () { if (isSupported) { window.navigator.geolocation.clearWatch(watchId.current); } }; }, []); return Object.freeze({ isSupported: isSupported, onChange: setOnChangeRef, onError: setOnErrorRef, }); }; exports.default = useGeolocationEvents;