Hello All, I'm getting Issue regarding Timeout in React.
My code.
submit() {
this.id1++;
this.array.push(this.state);
this.setState({value:""});
setTimeout(function() {
console.log(this.array);
}, 2000);
}
The Issue is.
When user clicks on submit state value has been push in array. But If I set Set timout to get Array list after 2 to 3 sec. It shows me Undefined.
Why is its saying that array is undefined. If I remove the timeout code then it works fine.
I dont know weather its my issue? Am I doing wrong?
Please help me out.
Thank you.
Why not just use this.state instead to push in this.array?
Because Im pushing the value in array.
this.array= []
this.state= {
id: 0,
value: ""
}
this.array.push(this.state)
I mean, why you don't leave this.array and use just this.state?
this.state is your source of truth. You don't need to pass its values to another object, got it? =)
I'm not sure what you're trying to do by pushing this.state into this.array as this doesn't look like idiomatic React code.
Your particular problem is because of how this works in JavaScript. If you're just calling setTimeout(function() { /* code here */ }), this inside the function will be different than your component. You can either capture it in a variable, bind the function, or you can use the arrow function syntax to preserve this. This article explains how this works in JavaScript.
I'm closing because it's not a bug in React, but a question about JavaScript. We recommend asking those on StackOverflow or support forums, as we use GitHub issues for tracking bugs in React.
Cheers!
Im very new to React So Dont know what is state why we use it. I just used it for making single object. Please let me know about State and props in React.
@Ghayyas follow the documentation =)
Alright So I got Resolved it By..
setTimeout(()=>{
console.log("Working :D ");
},3000);
Instead of:
setTimeout(function(){
console.log("Not Working BC :( ");
},3000);
Question is WHY?? :/
I explained why here: https://github.com/facebook/react/issues/9085#issuecomment-283349213.
You are using an arrow function to capture the value of this.
Please read about arrow functions on a resource like MDN. Cheers!