5

I have a component in react native:

export default class Screen extends Component {
  constructor(props){
    super(props);
    this.state = {
      prop1: false,
      prop2: simpleFunc
    };
  }
  simpleFunc = () => { /*...*/ }

  componentWillMount() {
      BackgroundGeolocation.on('location', this.onLocation);

The last line is callback method that will be called on new location.
From that method I can't access this.state or this.simpleFunc().

What should I do in order to update state from callback function?

1110
  • 7,829
  • 55
  • 176
  • 334

1 Answers1

6

In order to access this inside onLocation you need to bind the callback:

  componentWillMount() {
      BackgroundGeolocation.on('location', this.onLocation.bind(this));

or, you can use an arrow function (which will use the lexical scope of the parent):

  componentWillMount() {
      BackgroundGeolocation.on('location', (location) => this.onLocation(location));
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132