2

I have been trying to figure this out for a while now. I have three functions that all work in isolation. However, I cannot get the value from getUserCoordinates() to appear in fetchCurrentTemp(). It returns undefined no matter what I attempt. I've been outside of the JS environment for a minute, so perhaps I am missing something obvious but i am stumped.

fetchCurrentTemp()

import { getUserCoordinates } from './helpers';
const url = 'http://api.openweathermap.org/data/2.5';

export const fetchCurrentTemp = async () => {
    const coordinates = getUserCoordinates();
    console.log('coords:', coordinates);
    // logs 'undefined'
    try {
        let response = await fetch(`${url}/weather?APPID=x&lat=50.7498752&lon=-100.0004158&units=imperial`);
        let output = await response.json();
    } catch (error) {
        console.log(error);
    }
};

getUserCoordinates()

export const getUserCoordinates = () => {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(({ coords }) => {
            console.log(coords);
            //returns a value
            return coords;
        });
    } else {
        alert('Something is wrong');
    }
};

App

import React from 'react';
import { fetchCurrentTemp } from './utils/api_calls';

function App() {
    return (
        <div>
            <button onClick={() => fetchCurrentTemp()}>Hello</button>
        </div>
    );
}
kevin
  • 2,707
  • 4
  • 26
  • 58

2 Answers2

3

When you call return coords, you are merely returning out of the callback function, not out of getUserCoordinates().

You can use a Promise-based approach since getCurrentPosition is asynchronous:

export const getUserCoordinates = () => {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(({ coords }) => {
                console.log(coords);
                resolve(coords);
            });
        } else {
            reject('Something is wrong');
        }
    });
};

And then modify fetchCurrentTemp() to include await:

// --snip--
const coordinates = await getUserCoordinates();
// --snip--
aiyan
  • 406
  • 4
  • 11
3

I believe you need to return a promise on the getUserCoordinates. Otherwise, the return result will always be undefined.

Take a look on the example pen: https://codepen.io/lessadiogo/pen/ZEYqXRa

Cheers,

Diogo Lessa
  • 177
  • 5