Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access state from callback function [duplicate]

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?

like image 455
1110 Avatar asked Feb 02 '17 10:02

1110


1 Answers

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));
like image 105
Davin Tryon Avatar answered Sep 30 '22 06:09

Davin Tryon