Search code examples
android-sensorsreact-nativesensormanager

How to add a listener to a sensor in react-native?


I'm about to do my first steps in react-native development and I'm having problems with accessing the device's sensors. In my index.android.js, I'm doing

import {
  DeviceEventEmitter
} from 'react-native';

import { SensorManager } from 'NativeModules';
var mSensorManager = require('NativeModules').SensorManager;

export default class PropertyFinder extends Component {

  constructor(props) {
     super(props);

     this.state = {
       titleText: "Bird's Nest"
     };

     mSensorManager.startAccelerometer(100);

     DeviceEventEmitter.addListener('Accelerometer', function (data) {
       this.setState({ titleText: "ttt" })
     });
   }

  render() {...

...

I do get an error message when running the app on an emulator which is

undefined is not a function (evaluating 'this.setState({titleText:"ttt"})')

I did integrate the sensormanager in my project by loading

npm i react-native-sensor-manager --save

in the console, so the package should actually be recognized.

Do you have any idea of what the issue could be?

Thanks!


Solution

  • The addListener method adds another context to the callback function. You could use

    var that = this;
    DeviceEventEmitter.addListener('Accelerometer', function (data) {
      that.setState({ titleText: "ttt" })
    });
    

    or

    DeviceEventEmitter.addListener('Accelerometer', function (data) {
      this.setState({ titleText: "ttt" })
    }.bind(this));