Repo44
Repo44

Reputation: 75

Set API data to state

I am retrieving the data from api and filtering out only the data that I need. I am trying to set retrieved objects to state. Only the last object is set to state though

axios.get('http://api.openweathermap.org/data/2.5/forecast?zip=90210&APPID=MY_KEY&units=imperial')
      .then(res => {
        var data = res.data;
        var city = res.data.city.name;

        for (var i = 0; i < data.list.length; i += 8) {
          const filteredData = {
            city,
            date: data.list[i].dt_txt,
            expectedTemp: data.list[i].main.temp,
            minTemp: data.list[i].main.temp_min,
            maxTemp: data.list[i].main.temp_max,
            description: data.list[i].weather[0].main,
            icon: data.list[i].weather[0].icon,
            id: data.list[i].weather[0].id
          };

          this.setState({ data: filteredData });
        }
        console.log(this.state.data);
      })
      .catch(err => console.log(err));

Upvotes: 0

Views: 129

Answers (1)

Vencovsky
Vencovsky

Reputation: 31595

The reason why only the last is set is because on every loop, you override the setState. What you should do is keep it in an array and then setState with that array.

axios.get('http://api.openweathermap.org/data/2.5/forecast?zip=90210&APPID=badca0372074fc97fb1ceb2c2359eff5&units=imperial')
      .then(res => {
        var data = res.data;
        var city = res.data.city.name;

        let filteredDataArray = [] // data array

        for (var i = 0; i < data.list.length; i += 8) {
          const filteredData = {
            city,
            date: data.list[i].dt_txt,
            expectedTemp: data.list[i].main.temp,
            minTemp: data.list[i].main.temp_min,
            maxTemp: data.list[i].main.temp_max,
            description: data.list[i].weather[0].main,
            icon: data.list[i].weather[0].icon,
            id: data.list[i].weather[0].id
          };
          filteredDataArray.push(filteredData)  // add to the array        
        }
        this.setState({ data: filteredDataArray }); // setState with the data array
        console.log(this.state.data);
      })
      .catch(err => console.log(err));

Upvotes: 1

Related Questions