Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs how to initialize array object in state

I'm new to reactjs and i'm learning to change state in reactjs. I'm trying to initialize an array object in state with unknown length, and later update the array object using set state. Following is the code:

state = {
  error: null,
  temperature: null,
  isLoaded: false,
  Weather5days: [],
};

So I have initialized Weather5days as an array, with unknown length. I get the data for Weather5days through API as json, so after fetch, I do this:

then(json => {
  var newArr = json.Forecasts.map(function(val) {
    //Forecasts have length of 5 array
    return {
      date: val.Date,
    };
  });

  console.log(newArr); // I checked, data is copied correctly in newArr.

  this.setState({
    Weather5days: newArr, //set state of the weather5days
  });
});

Now above code works with no error, but when I call console.log(this.state.Weather5days), the array is empty. So I thought the way of initializing Weather5days was wrong so I tried the following:

state = {
  error: null,
  temperature: null,
  isLoaded: false,
  Weather5days: [{}, {}, {}, {}, {}], //array object of length 5
};

and It works. This is half the solution because in certain circumstances, you don't know the length of the array(that comes from the API) and I cannot afford to do literally do [{},{}..] everytime. What is the proper way of initializing array object with unknown length in state?

like image 749
Eric Ahn Avatar asked Oct 17 '22 14:10

Eric Ahn


1 Answers

Hi your defined the Weather5days as empty array and adding the newArr to it but you should take the previous state of array and add your newArr to the state like this

this.setState({
Weather5days : [...this.state.Weather5days, newArr]
})
like image 198
user3379150 Avatar answered Nov 03 '22 09:11

user3379150