Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update geolocation state in React?

Tags:

reactjs

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

}
like image 365
XHZ Avatar asked Aug 13 '26 15:08

XHZ


1 Answers

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.

like image 99
Nick Avatar answered Aug 16 '26 19:08

Nick