React setState won't update

2.3k views Asked by At

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);
}
2

There are 2 answers

1
Ivan Minakov On BEST ANSWER

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));
3
Nocebo On

setState is asynchronous:

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

Use the callback of setState to determine changes