0

I'm trying to get W3C Sensors API working inside my React Web App (Not React Native), basically I cannot find any reliable documentation for getting it to work using javascript, this is the code I produced so far:

  import React, { Component } from "react";

  export default class Postion extends Component {
  state = {
    message: "not supported",
  };
  componentDidMount() {
    this.test();
  }

  test(){
    if(window.Accelerometer){
        this.setState({message:"supported"})
    }
  }

  render() {
    return <div>{this.state.message}</div>;
  }
}

It displays "supported" on desktop browsers and "not supported" on all the mobile browser I tried so far, so my question is: how can I get data from the accelerometer using the sensors API (especially on mobile browsers)? I can even be done? Thanks.

Giulio Serra
  • 253
  • 1
  • 6
  • 15

1 Answers1

0

I haven't used it yet. But there's nice documentation always on MDN:

let acl = new Accelerometer({frequency: 60});

acl.addEventListener('reading', () => {
  console.log("Acceleration along the X-axis " + acl.x);
  console.log("Acceleration along the Y-axis " + acl.y);
  console.log("Acceleration along the Z-axis " + acl.z);
});

acl.start();

Now, to implement it on React, you know the deal. Just need to hook in componentDidMount hook.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231