Reputation: 13
I need to put an if condition with throw inside a fetch - .then function, to check if the response data is correct are not, but I don't know how to do.
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,
})
})
};
Upvotes: 0
Views: 2330
Reputation: 2106
Like this:
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.log(err));
Upvotes: 1
Reputation: 10264
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.log(err) });
you can use catch()
with fetch API
Upvotes: 0