• 1000 и верните обещание.
В ComponentDidMount
я вызвал функцию с помощью await, потому что она возвращает мне обещание, после чего у меня есть значение, затем я устанавливаю состояние
и вызываю другое getWeather
Функция
import React from "react";
import axios from "axios";
// import WeatherGadget from './weather.component'
export default class WeatherApi extends React.Component {
constructor(props) {
super(props);
this.state = {
city: null,
lat: 0,
lon: 0,
wind: 0,
weather: 0,
icon: null
};
}
async componentDidMount() {
const location = await this.location();
location && this.setState({ lat: location.lat, lon: location.long });
location && this.getWeather();
}
location = () => {
//return the promise that contain the navigator object
return new Promise((resolve, reject) => {
try {
navigator.geolocation.getCurrentPosition(position => {
resolve({
lat: position.coords.latitude,
long: position.coords.longitude
});
});
} catch (error) {
let temp = {
lat: 24.8607,
long: 67.0011
};
reject(temp);
}
});
};
//calling weather api
getWeather = async () => {
const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${
this.state.lat
}&lon=${this.state.lon}&appid=8821HIDDEN4e9d78`;
console.log("url", url);
try {
const res = await axios.get(url);
if (res) {
console.log("res", res.data)
const weatherObj = res.data;
console.log("===", weatherObj);
const currentWeather = weatherObj.current.temp;
const windSpeed = weatherObj.current.wind_speed;
const icon = weatherObj.current.weather[0].icon;
this.setState({ wind: windSpeed, weather: currentWeather, icon: icon });
}
} catch (error) {
console.log("error", error)
}
};
render() {
return (
<div>
{/* <WeatherGadget city={this.state.city} wind ={this.state.wind} weather={this.state.weather} icon={this.state.icon}/> */}
<p> Lat: {this.state.lat}</p>
<p> Lng: {this.state.lon}</p>
<p> Weather: {this.state.weather}</p>
<p>Wind: {this.state.wind}</p>
</div>
);
}
}