I have an array of 16 objects which I declare as a state in the constructor:
this.state = {
todos:[...Array(16)].map((_, idx) => {
return {active: false, idx}
}),
}
Their status will get updated through an ajax call in ComponentDidMount.
componentDidMount()
{
var newTodos = this.state.todos;
axios.get('my/url.html')
.then(function(res)
{
newTodos.map((t)=>{
if (something something)
{
t.active = true;
}
else
{
t.active = false;
}
}
this.setState({
todos:newTodos,
})
}
}
and then finally, I render it:
render(){
let todos = this.state.todos.map(t =>{
if(t.active === true){
console.log('true'}
else{
console.log('false')
}
})
return (
<div></div>
)
}
They all appear as active = false in the console, they never go into the if condition. When I print out the entire state it appears not to be updated in the render method. In the console it says "value below was just updated now".
I thought changes to the state in ComponentWillMount will call the render function again?
How do I make that React will accept the new values of the state?

componentWillMountcode? At a first look, it seems like thethis.setStatecall is being called after the axios call, but the code you are sharing is neither aligned property, nor are all blocks closed so it's hard to say if thesetStateis being done from inside yourthenblock or from inside thecomponentWillMountdirectly. If it's from thethenyou want to call it, you either have to use arrow functions or save thethiscontext, if it's from thecomponentWillMountthen you shouldawaitthe axios call and makecomponentWillMountasyncmapreturns a new array, it doesn't mutate in place. In the end yournewTodosare still your oldthis.state.todos. And you still need to store thethiscontext if you are not using arrow functions in thethencallback (oh, and it's still not properly closed, thethenfunction misses a), but the alignment did the trick)[...Array(16)].map, cool trick. For those who don't know,Array(16).mapdoesn't actually iterate over any of the items because they are empty slots stackoverflow.com/questions/27433075/…