I'm trying to get a user's geolocation and update the state with the latitude and longitude. I followed the MDN docs for the Geolocation API, but I'm getting an error that success is undefined, even though I defined it according to the docs. How can I make this code work?
class App extends React.Component {
state = { latitude: null, longitude: null };
componentDidMount() {
window.navigator.geolocation.getCurrentPosition(
success => this.state.latitude =
success.coords.latitude, this.state.longitude = success.coords.longitude
);
}
render() {
return <div>{this.state.latitude}, {this.state.longitude}</div>;
}
}
This error can be a bit confusing in the console because the error is not actually in regards to success, but rather this referencing success. You are not assigning the state correctly. You must change state using setState. You cannot change state by directly assigning it a new value.
class App extends React.Component {
state = { latitude: null, longitude: null };
componentDidMount() {
window.navigator.geolocation.getCurrentPosition(
success => this.setState({ latitude: success.coords.latitude, longitude: success.coords.longitude })
);
}
render() {
return <div>{this.state.latitude}, {this.state.longitude}</div>;
}
}
You can read more about the keyword this here. It's a very important concept to understand if you are going to be working in React.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With