0

I am using metaweather.com API to build a Web Application. I want to show 6 cities on the home page; I guess I have to call the API 6 time and push the data in an array like allCitiesDetails. How I have to do that? If there is a better way, please tell me. Here is my code :

state = {
    city: {
      cityname: this.props.value
    },
    woeid: '',
    todayWeather: [],
    weatherDetails: [],
    allCitiesDetails: []
  };
  getCity = (cityName) => {
    var self = this;
    axios
      .get('https://www.metaweather.com/api/location/search/?query=' + cityName)
      .then(response => {
        self.setState({
          woeid: response.data[0].woeid
        });
        self.getWeather(response.data[0].woeid);
      })
      .catch(function(error) {
        alert('No results were found. Try changing the keyword!');
      });
  }

  getWeather = async (woeid) => {
    const { data: weatherDetails } = await axios.get(
      'https://www.metaweather.com/api/location/' + woeid
    );
    this.setState({
      weatherDetails,
      todayWeather: weatherDetails.consolidated_weather[0]
    });
  }
Meet Zaveri
  • 2,921
  • 1
  • 22
  • 33
Kalagar
  • 379
  • 2
  • 6
  • 18
  • You can refer this: https://stackoverflow.com/a/37576787/441528 – Tu Tran Oct 17 '18 at 06:49
  • Please tell us where are you having problems exactly. Have you been able to show at least one result? have you tried pushing the result to an array and show the contents of that array? – c-chavez Oct 17 '18 at 07:49

2 Answers2

1

You should make 6 different promises and use Promise.all to get the weather of all 6 cities in parallel. You can do this as :

const getWeatherFromWoeid = cityName => axios.get(`https://www.metaweather.com/api/location/${woeid}`);

....

const p1 = getWeatherFromWoeid(woeid1);
const p2 = getWeatherFromWoeid(woeid2);
const p3 = getWeatherFromWoeid(woeid3);
const p4 = getWeatherFromWoeid(woeid4);
const p5 = getWeatherFromWoeid(woeid5);
const p6 = getWeatherFromWoeid(woeid6);

Promise.all([p1,p2,p3,p4,p5,p6])
    .then(([result1, result2, result3, result4, result5, result6]) => {
         ...set result in the state   
    })
    .catch((err) => {
       ...handle error
    })

Also, always use catch if you're using promises or async

Ajay Gaur
  • 5,140
  • 6
  • 38
  • 60
0

instead of using state inside the api call...

self.setState({
      woeid: response.data[0].woeid
    });

you can push the values in dummy array then outside the api call u can set state.

Vivek Chaudhari
  • 1,930
  • 1
  • 14
  • 20