Search code examples
reactjsgeolocationfetches6-promisereact-lifecycle

How do I get user's location via navigator.geolocation before my fetch executes in componentDidMount() in react.js?


I have tried this a variety of different ways but am getting stumped. New to using promises and making api calls in react. This is what I have at the moment:

import React, { Component } from 'react'
import Column from './Column'
import { CardGroup } from 'reactstrap';

let api = "https://fcc-weather-api.glitch.me/api/current?";


class App extends Component {

    constructor(props) {
        super(props)
        this.state = {
            isLoaded: false,
            items: {},
        }

    this.fetchWeather = this.fetchWeather.bind(this)
}

fetchWeather(apiStr) {
    fetch(apiStr)
        .then(res => res.json())
        .then(

            (result) => {

                console.log(result)
                this.setState({
                    isLoaded: true,
                    items: result.main
                });
                console.log(this.state);
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                });
            }
        )

}

componentDidMount() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            api += `lat=${position.coords.latitude}&lon=${position.coords.longitude}`;     
        })
        this.fetchWeather(api);
    }
}

Right now the api call is being executed before getting the current position. I have tried various ways and havn't been able to access the current position before the fetch executes. Whats the best way to handle this? Any insights on this would be really appreciated. Any questions, let me know.Thanks.


Solution

  • Since getting the location is done with a callback you must fetch inside the callback

    navigator.geolocation.getCurrentPosition((position) => {
      api += `lat=${position.coords.latitude}&lon=${position.coords.longitude}`;
      this.fetchWeather(api);
    });