Reputation: 53
I am passing props from a child component B to parent component A. And then from parent component A passing it to child component C. When I'm passing the data from component B to A it is all fine. But when I try to set a state to data received from component B in parent Component A the state is not being set immediately.
I have binded the functions in all the components.
Below is the code of function I'm using.
In component A:
onchange=(data) => {
this.setState({
selectedvalue: data
});
console.log(data)
console.log(this.state.selectedvalue)
}
On the initial render I get the correct value in console.log(data)
but receive undefied
in console.log(this.state.selectedvalue)
. When the data is changed console.log(this.state.selectedvalue)
displays the initial value console.log(data)
has shown. i.e the state is being set after an interaction and not at the same time.
I want to pass the attribute selectedvalue
to another child component C.
But with the state not being set instantly I'm unable to pass the data the moment it is changed.
Is there any way how I can pass the data from child component B to child component C through parent component A?
Upvotes: 2
Views: 1406
Reputation: 11270
setState
is async, you can access the updated value in the callback
:
this.setState({
selectedvalue: data
}, () => console.log(this.state.selectedvalue));
If you pass this.state.selectedvalue
to the child component as a prop, the child component will automatically be re-rendered with the updated value whenever this.state.selectedvalue
changes (unless you explicitly ignore it with shouldComponentUpdate
).
Upvotes: 1