Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing this.state in React-Native

Hi I'm new to React so bear with me. I'm want to store geoposition as a state. Seems nifty since any change in position will trigger a render, which is exactly what I want. During development I have a button that manual triggers the event by accessing the lastPosition. But when I do. The state is "undefined". Any clue why?

export default class FetchProject extends Component {
    constructor(props) {
        super(props);
        this.state = {
            initialPosition: 'unknown',
            lastPosition: 'unknown',
        };
    }

    //code that sets lastposition
    componentDidMount() {
        ....
    }

    _onPressGET (){
        console.log("PressGET -> " + this.state); //undefined
        var northing=this.state.initialPosition.coords.latitude; 
        //triggers error
    }

    render() {
       return (    
           <View style={styles.container}>
               <TouchableHighlight onPress = {this._onPressGET} style = {styles.button}>
                  <Text>Fetch mailbox</Text>
               </TouchableHighlight>
           </View>
       );
    }
}
like image 541
TOMvonMOM Avatar asked Oct 31 '16 11:10

TOMvonMOM


People also ask

What is the difference between state and props in React Native?

React Native - State. The data inside React Components is managed by state and props. In this chapter, we will talk about state. Difference between State and Props. The state is mutable while props are immutable. This means that state can be updated in the future while props cannot be updated.

How to change the state of a React state object?

React State 1 Creating the state Object. 2 Using the state Object. 3 Changing the state Object. To change a value in the state object, use the this.setState () method. When a value in the... More ...

Why can’t I access the latest state when using React hooks?

If you’re using React hooks in a component with an event listener, your event listener callback cannot access the latest state. We can incorporate useRef to solve this problem.

How to wait for React state to update?

As setState is an operation, you can just wait till the value is set by React. You might wait for a certain period to access the updated state using


1 Answers

When using ES6 classes in RN, watch for binding this - this may not be what you think unless you bind it.

onPress = { this._onPressGet.bind(this) }

or in the constructor

constructor(props) {
  super(props);

  this.state = {
    initialPosition: 'unknown',
    lastPosition: 'unknown'
  };

  this._onPressGet = this._onPressGet.bind(this);
}

or maybe the most elegant way

_onPressGet = () => {
  // Function body
}

In order from least to most preferential.

like image 84
Daniel Broad Avatar answered Sep 25 '22 13:09

Daniel Broad