0

I'm trying to set the state from within the if statement but it wont do this. In result I need to update state from within if statement where I can receive longitude and latitude coordinates, but it won't save the state. If I echo in console outside of if statement I will read only first setState value form componentWillMount. What's the issue there? What I'm doing wrong here? So here is the structure:

componentWillMount() {
    this.setState({
        location: {
            name: 'Riga'
        }
    });
}

componentDidMount() {
    if (!!navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {

            this.setState({
                location: {
                    name: 'Sigulda'
                }
            });
        });
    } else {
        alert('ERROR on GEOLOCATION');
    }

    console.log(this.state.location);
}
Sangsom
  • 437
  • 2
  • 6
  • 16
  • Possible duplicate of https://stackoverflow.com/questions/41278385/this-setstate-doesnt-mutate-state-immediately/41278440#41278440 – Shubham Khatri Aug 29 '17 at 07:45

2 Answers2

5

setState actions are asynchronous.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

You should use setState callback function:

this.setState({
  location: {
    name: 'Sigulda'
  }
}, () => console.log(this.state.location));
Ivan Minakov
  • 1,432
  • 7
  • 12
3

setState is asynchronous:

 this.setState({
                location: {
                    name: 'Sigulda'
                }
            }, () => console.log(this.state.location));

Use the callback of setState to determine changes

Nocebo
  • 1,927
  • 3
  • 15
  • 26
  • 1
    Perfect ans.. setState is async and you can pass a callback here as demonstrated above incase you want to use the updated state – Nitish Phanse Aug 29 '17 at 06:40
  • Thank you for explanation, that solved my issue!!! – Sangsom Aug 29 '17 at 06:48
  • 1
    You might run into other issues though, like @MayankShukla already said. I'm not familiar with you `geolocation` but your `setState` issue is fixed – Nocebo Aug 29 '17 at 06:49