-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathuseDeviceMotion.ts
38 lines (33 loc) · 1008 Bytes
/
useDeviceMotion.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useEffect, useState } from 'react';
import { EventArgs } from './types';
import { managedEventListener } from './utils';
// Source: https://w3c.github.io/deviceorientation/#dictdef-devicemotioneventinit
const initialState: EventArgs<DeviceMotionEvent> = {
acceleration: null,
accelerationIncludingGravity: null,
rotationRate: null,
interval: 0,
};
/**
* Tracks acceleration and rotation rate of the device.
*
* @returns Own properties of the last corresponding event.
*
* @example
* function Component() {
* const { acceleration, rotationRate, interval } = useDeviceMotion();
* // ...
* }
*/
export default function useDeviceMotion(): EventArgs<DeviceMotionEvent> {
const [motion, setMotion] = useState(initialState);
// TODO: Request permission if necessary, see https://github.com/w3c/deviceorientation/issues/57
useEffect(
() =>
managedEventListener(window, 'devicemotion', event => {
setMotion(event);
}),
[],
);
return motion;
}