window DeviceMotion event using React

426 Views Asked by At

I'm not able to trigger the DeviceMotion function in React app when I move my browser. I'm using window object devicemotion event to achieve the functionality.

Excerpt from my code

export default function App() {
  const [x, setX] = useState("");
  const [y, setY] = useState("");
  const [z, setZ] = useState("");

  function handleMotionEvent(event) {
    console.log("handle motion event", event);

    var x = event.accelerationIncludingGravity.x;
    var y = event.accelerationIncludingGravity.y;
    var z = event.accelerationIncludingGravity.z;

    setX(x);
    setY(y);
    setZ(z);
  }

  useEffect(() => {
    window.addEventListener("devicemotion", handleMotionEvent, true);
  }, [x, y, z]);

  return (
    <div className="App">
      <h1>Device Motion</h1>
      <div>
        X - {x} Y - {y} Z - {z}
      </div>
    </div>
  );
}

I created a working example using CodeSandbox. Could anyone please help?

1

There are 1 best solutions below

1
Gonzalo Botero On

The problem is that you are not using SSL cert, you have to set your react App to use an SSL cert, the instructions can be found in this link https://www.makeuseof.com/create-react-app-ssl-https/ once you run with the SSL cert your mobile browser will read de accelerometers data, I hope this help.