0

Without attempting to update my state, the initial location in state is presented correctly. When I set state using a helper function, nothing is displayed in my app. What am I doing wrong? Additionally, logging props inside ShowLocation's render() shows that the coords{lat:xx,long:xx} are coming through correctly.

App.js

import * as helpers from './src/helpers';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = globals.initial_state;
  }

  componentDidMount(){
    this.setState({location:helpers.getLocation()});
  }

  render() {
    return (
      <View>
        <ShowLocation coords={this.state.location} />
      </View>
    );
  }
}

ShowLocation.js

class ShowLocation extends Component {
    constructor(props){
        super(props);
    }

    render(){
        return(
            <View>
                <Text>{this.props.coords.lat}, {this.props.coords.long}</Text>
            </View>
        )
    }
};

helpers.getLocation:

export function getLocation(){
    coords = {};
    navigator.geolocation.getCurrentPosition(
        (position) => {
            coords['lat'] = position.coords.latitude
            coords['long'] = position.coords.longitude
        },
        (error) => this.setState({ navigatorError: error.message }),
        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
    return coords;
}
smilebomb
  • 5,123
  • 8
  • 49
  • 81
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – bennygenel Jul 13 '18 at 14:01

1 Answers1

-1

Did you tried:

componentDidMount(){
  this.setState({ location: getLocation().bind(this) });
}

Or, same thing, but cleaner code:

constructor() {
  // other stuff
  this.getLocation = getLocation().bind(this)
}

componentDidMount(){
  this.setState({ location: this.getLocation() });
}

Edit:

You must import { getLocation} from 'path/of/file'

Poptocrack
  • 2,879
  • 1
  • 12
  • 28