UNPKG

web-api-hooks

Version:

Essential set of React Hooks for convenient Web API consumption.

28 lines (27 loc) 861 B
import { useEffect, useState } from 'react'; /** * Tracks geolocation of the device. * * @param options Additional watching options. * @param errorCallback Method to execute in case of an error, e.g. when the user denies location sharing permissions. * @returns Locational data, or `undefined` when unavailable. * * @example * function Component() { * const geolocation = useGeolocation(); * if (geolocation) { * const { coords } = geolocation; * } * // ... * } */ export default function useGeolocation(options, errorCallback) { const [position, setPosition] = useState(); useEffect(() => { const id = navigator.geolocation.watchPosition(setPosition, errorCallback, options); return () => { navigator.geolocation.clearWatch(id); }; }, [errorCallback, options]); return position; }