Jonas Bergner
Jonas Bergner

Reputation: 1743

How do i use componentWillReceiveProps() correctly?

I'm trying to update a child component as soon as it recieves new props. However, componentWillReceiveProps() in my child component is called before the props have actually updated. After reading this article i do understand why but it doesn't explain me how to solve my problem.

How do i call componentWillReceiveProps() after the props have updated?

Right now i'm cheating my way around it by letting a timeout run which waits for the actual update, but i really don't like this solution.

  componentWillReceiveProps(){
   var timeOut = setTimeout(() => this.loadPosts(), 100)
  },

Thanks id advance!

Upvotes: 3

Views: 13320

Answers (2)

Josh
Josh

Reputation: 756

Is it necessary to call componentWillReceiveProps after the props have updated? Or can you use the nextProps argument?

Eg. if you rewrite as:

componentWillReceiveProps(nextProps){
  this.loadPosts(nextProps)
},

and then of course also rewrite the signature of loadPosts to allow manually passing in props:

loadPosts(props = this.props){
  // do something with props
  ...
}

Upvotes: 8

Andrés Andrade
Andrés Andrade

Reputation: 2223

Use componentDidUpdate(prevProps, prevState). When it's called, two arguments are passed: prevProps and prevState. This is the inverse of componentWillUpdate. The passed values are what the values were, and this.props and this.state are the current values.

Upvotes: 4

Related Questions