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?
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]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With