2

I want to get location information by using Geolocation API in react.

I made a button to get location info in this code.

import React, { Component } from 'react'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      latitude: null,
      longitude: null,
    }
  }

  position = async () => {
    await navigator.geolocation.getCurrentPosition(
      position => this.setState({ 
        latitude: position.coords.latitude, 
        longitude: position.coords.longitude
      }), 
      err => console.log(err)
    );
    console.log(this.state.latitude)
  }

  render() {
    return (
      <div>
        <button onClick={this.position} className='Filter'>Filter</button>
      </div>
    );
  }
}

export default App;

Once I pressed a button, console shows null. However, when I pressed a button again, the console shows location info.

Do you have any idea why I couldn't get the location info for the first time?

nima
  • 7,796
  • 12
  • 36
  • 53
gnxvw
  • 404
  • 1
  • 9
  • 23

1 Answers1

11

setState is an asynchronous function.

When you call position the first time, the state is eventually updated. The second time it is already there, which is why it gets logged.

You can move the logging to the second parameter of setState, which is a callback.

this.setState({ 
    latitude: position.coords.latitude, 
    longitude: position.coords.longitude
  }, newState => console.log(newState))
Kraylog
  • 7,383
  • 1
  • 24
  • 35
  • Thank you for your comment. I put `setState` in `componentWillMount`, and I could solve it!! – gnxvw Apr 21 '19 at 08:04
  • @gnxvw You could just `await` the `setState` call, assuming you declare the `getCurrentPosition` callback as `async`. – Josh Hale Apr 21 '19 at 10:01