I have three functions: [getLocation, getWeather, displayWeather]
I would like displayWeather to use async, and call the other functions, but i'm getting an error from getWeather(), stating something went wrong from reject().
I understand there's an issue somewhere getting lat, lon positions, but can't figure out where my issues are coming from.
Definitely new to JS Promises, and would love some support.
Thanks very much
import Card from "../Card/Card";
import { useState } from "react";
const WeatherCard = () => {
const [location, setLocation] = useState([]); // array default
const getLocation = () => {
return new Promise((resolve, reject) => {
// if location is enabled in browser
if (navigator.geolocation) {
// get [lat, lon] coordinates, passes to setLocation()
resolve(
navigator.geolocation.getCurrentPosition((position) => {
// set location state to array [lat, lon]
setLocation([position.coords.latitude, position.coords.longitude]);
})
);
// if location isn't enabled in browser
} else {
// error message
reject(console.log("Please enable location services"));
}
});
};
// takes in location [lat, lon] and returns weather data
const getWeather = (lat, lon) => {
return new Promise((resolve, reject) => {
// if location state has values
if (location.length > 0) {
resolve(
// get data from api (api key is in .env file)
fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude={part}&appid=${process.env.REACT_APP_WEATHER_API_KEY}`
)
// parse data to json
.then((res) => res.json())
.then((data) => {
// write weather data to console
console.log(data);
})
);
// if location state has no values
} else {
// error message
reject(console.log("Something went wrong getting the api"));
}
});
};
// displays weather data to user (async function)
const displayWeather = async () => {
// get location
await getLocation();
//pass in location state [lat, lon] to getWeather()
await getWeather(location[0], location[1]).catch((err) => console.log(err));
};
// rendered elements
return (
<Card>
<div>{location}</div>
<button onClick={displayWeather}>Click</button>
</Card>
);
};
export default WeatherCard;