Reputation: 362
Why I'm getting undefined if I called console log
after this.setState
for the same state in componentWillMount
this example will explain the problem
constructor(props){
super(props);
this.state = {
total: 100,
length: null,
number: null,
}
}
componentWillMount(){
let JSONFetchedNumber = 30.20;
this.setState({length: JSONFetchedNumber});
console.log(this.state.length);// getting Null response
let collect = this.state.total/this.state.length;
let result = collect.toFixed(0)/1+1;
this.setState({number: result});// This won't work cus length state in undefined
}
render() {
console.log(this.state.length);// getting 30.20 Successfully
why I can't use the state of this.setState
instantly in componentWillMount
? it works only in render
I have tried to use componentDidMount
it wont works. Only in render works and my problem here that I can't use this.state in render
Upvotes: 0
Views: 55
Reputation: 1049
this.setState is an Async function. You are trying to access it before the state is updated. So whatever manipulations you want to do on the state, you can do it in callback function.
this.setState({length:JSONFetchedNumber},()=>{
//Your code which is using state
console.log(this.state)
})
Upvotes: 1
Reputation: 1820
this.setState is an async function, it takes time to complete. If you want to log the state, the precise way is to log it in the callback of this.setState. This should work,
this.setState({length: JSONFetchedNumber}, ()=> console.log(this.state.length););
Upvotes: 1
Reputation: 650
You should not use length as a keyword in javascript, I'm pretty sure it's your error.
var.length
is a tool in javascript to get the actual length of a variable, there must be a conflict there.
Upvotes: -1