Мне нужно поставить условие if с throw внутри функции fetch - .then, чтобы проверить правильность данных ответа, но я не знаю, как это сделать.
getWeather = (latitude, longitude) => {
const API_KEY = "";
const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
fetch(api)
.then(response => response.json())
.then(data => {
this.setState({
locationName: data.name,
temperature: data.main.temp,
weatherDescription: data.weather[0].description,
isLoading: false,
})
})
};
fetch(api)
.then(response => response.json())
.then(data => {
this.setState({
locationName: data.name,
temperature: data.main.temp,
weatherDescription: data.weather[0].description,
isLoading: false,
})
})
.catch(error=> { console.info(err) });
вы можете использовать catch()
с fetch API
@Roy.B, может быть, я не местный, и этот парень тоже не местный (может быть, вьетнамец), так что это выглядит по-английски Проблема
Так:
fetch(api)
.then(response => response.json())
.then(data => {
if (**YOUR_CONDITION_HERE**){
this.setState({
locationName: data.name,
temperature: data.main.temp,
weatherDescription: data.weather[0].description,
isLoading: false,
} else {
throw new Error("data invalid");
}).catch(err => console.info(err));
@HuyNguyen, как это у тебя работает? вы просили "если условие с броском внутри выборки"...