joethemow
joethemow

Reputation: 1773

Why is the child component not updating with state of parent?

I am passing my parent state to my child component, but when I print props in the child component I get the previous state of the parent component instead of the most up to date state. I'm pretty sure it's because this.setState is asynchronous.

  handleClick(event) {
   const value = event.currentTarget.value;
   this.setState({ touched: value });
  }

 render() {
  return(
   <ChildComponent {...this.state} />
  )

 }

Upvotes: 2

Views: 2708

Answers (1)

John Ruddell
John Ruddell

Reputation: 25842

componentWillReceiveProps is before component update render. If you read the docs they explain you have a reference to the next props coming in.

componentWillReceiveProps(nextProps, nextState){
    this.props.something // old value
    nextProps.something // new value
}

now did update happens after the render finishes.

componentDidUpdate(previousProps){
    this.props.somehting // new value
    previousProps.something // old value
}

your issue is you are printing out the old props before the new ones have a change to update the old ones. what you need is either componentDidUpdate or look at the next props coming in

Upvotes: 5

Related Questions