UNPKG

beautiful-react-hooks

Version:

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

56 lines (55 loc) 2.8 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 useGeolocationEvents_1 = __importDefault(require("./useGeolocationEvents")); var geolocationUtils_1 = require("./shared/geolocationUtils"); /** * Returns a frozen object containing the `position` object, the `isSupported` boolean flag, reporting whether the * geolocation API is supported or not and the `isRetrieving` boolean flag reporting whether the hook is fetching the * current position. * The position is retrieved by using the * [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API), * when supported.<br/><br /> * It possibly accepts an object of [geolocation options] * (https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) to be used as parameter when using the * `Geolocation.getCurrentPosition()` method. */ var useGeolocationState = function (options) { if (options === void 0) { options = geolocationUtils_1.geoStandardOptions; } var _a = (0, react_1.useState)(false), isRetrieving = _a[0], setRetrieving = _a[1]; var _b = (0, react_1.useState)(null), position = _b[0], setPosition = _b[1]; var _c = (0, useGeolocationEvents_1.default)(options), isSupported = _c.isSupported, onChange = _c.onChange, setOnGeolocationEventsErrorRef = _c.onError; var _d = (0, createHandlerSetter_1.default)(), onCurrentPositionErrorRef = _d[0], setOnCurrentPositionErrorRef = _d[1]; var savePosition = (0, react_1.useCallback)(function () { if (position === null) { setRetrieving(true); navigator.geolocation.getCurrentPosition(function (nextPosition) { if (!(0, geolocationUtils_1.isSamePosition)(position, nextPosition)) { setPosition((0, geolocationUtils_1.makePositionObj)(nextPosition)); setRetrieving(false); } }, function (err) { if (onCurrentPositionErrorRef.current) { onCurrentPositionErrorRef.current(err); } }); } }, [position]); (0, react_1.useEffect)(savePosition, [position]); onChange(savePosition); var onError = function (callback) { setOnCurrentPositionErrorRef(callback); setOnGeolocationEventsErrorRef(callback); }; return Object.freeze({ onError: onError, isSupported: isSupported, isRetrieving: isRetrieving, position: position, }); }; exports.default = useGeolocationState;