Kalagar
Kalagar

Reputation: 379

store each api response in an array in React

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]
    });
  }

Upvotes: 0

Views: 567

Answers (2)

Vivek Chaudhari
Vivek Chaudhari

Reputation: 2010

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.

Upvotes: 0

Ajay Gaur
Ajay Gaur

Reputation: 5270

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

Upvotes: 1

Related Questions