Как поместить условие if с помощью throw в метод fetch ... then API - PullRequest
0 голосов
/ 29 мая 2019

Мне нужно поставить условие 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, 
        })

      })
  };

Ответы [ 2 ]

1 голос
/ 29 мая 2019

Как это:

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));
0 голосов
/ 29 мая 2019
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) });

вы можете использовать catch() с fetch API

...