UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

42 lines 1.6 kB
import { useState, useEffect } from 'react'; import { useEventListener } from '../event-handling/useEventListener'; // Assuming useEventListener is in the same directory const initialState = { acceleration: null, accelerationIncludingGravity: null, rotationRate: null, interval: null, isSupported: false, }; /** * Tracks device motion information like acceleration and rotation rate. * Requires HTTPS and often user permission. * Uses the `devicemotion` event. * * @returns {DeviceMotionState} The current state of device motion. */ export const useDeviceMotion = () => { const [state, setState] = useState(initialState); const [isSupported, setIsSupported] = useState(false); useEffect(() => { // Feature detection if (typeof window !== 'undefined' && 'DeviceMotionEvent' in window) { setIsSupported(true); } else { setIsSupported(false); } }, []); const handleMotionChange = (event) => { setState({ acceleration: event.acceleration, accelerationIncludingGravity: event.accelerationIncludingGravity, rotationRate: event.rotationRate, interval: event.interval, isSupported: true, // We know it's supported if we get an event }); }; useEventListener('devicemotion', handleMotionChange, undefined, isSupported); // Combine internal isSupported with the rest of the state for the return value return Object.assign(Object.assign({}, state), { isSupported }); }; //# sourceMappingURL=useDeviceMotion.js.map