Skip to content

Latest commit

 

History

History
106 lines (88 loc) · 3.18 KB

use-magnetometer.md

File metadata and controls

106 lines (88 loc) · 3.18 KB

useMagnetometer

Track changes in the magnetic field with Magnetometer

releases builds demo

Other hooks   —   Usage   —   Changelog


expo install @use-expo/sensors expo-sensors

Usage

// full hook
const [data, isAvailable] = useMagnetometer();
const [data, isAvailable] = useMagnetometerUncalibrated();

// other options
useMagnetometer({ interval: 1000 });
useMagnetometer({ initial: { x: 1, y: 1, z: 1 } });
useMagnetometer({ availability: false });

// or use the raw data with:
useMagnetometerUncalibrated();
useMagnetometerUncalibrated({ interval: 1000 });
useMagnetometerUncalibrated({ initial: { x: 1, y: 1, z: 1 } });
useMagnetometerUncalibrated({ availability: false });

Example

import { useMagnetometer } from '@use-expo/sensors';
import { Text, View } from 'react-native';

function MagnetometerSensor() {
    const [data, available] = useMagnetometer({ interval: 100 });

    return (
        <View>
            <Text>Magnetometer:</Text>
            {(available && data)
                ? <Text>x: {round(data.x)} y: {round(data.y)} z: {round(data.z)}</Text>
                : <Text>unavailable</Text>
            }
        </View>
    );
}

function round(value = 0) {
    return Math.floor(value * 100) / 100;
}

API

import { ThreeAxisMeasurement } from 'expo-sensors';

function useMagnetometer(options?: Options): Result;
function useMagnetometerUncalibrated(options?: Options): Result;

interface Options {
    /** The initial data to use before the first update. */
    initial?: ThreeAxisMeasurement;
    /** If it should check the availability of the sensor, defaults to `true`. */
    availability?: boolean;

    /**
     * The interval, in ms, to update the magnetometer data.
     * Note, this is set globally through `Magnetometer.setUpdateInterval`.
     * When used in 2 or more components, only the last rendered component's interval will be used for all.
     */
    interval?: number;
}

type Result = [
    ThreeAxisMeasurement | undefined,
    boolean | undefined,
];

with ❤️ byCedric