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);
}
setState
actions are asynchronous.You should use
setState
callback function: