Huy Nguyen
Huy Nguyen

Reputation: 13

How to put the if condition with 'throw' in a fetch...then API

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

Answers (2)

Roy.B
Roy.B

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

kyun
kyun

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

Related Questions