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]
    });
  }
2
  • You can refer this: stackoverflow.com/a/37576787/441528 Commented Oct 17, 2018 at 6: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? Commented Oct 17, 2018 at 7:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.