Saurabh Agrawal
Saurabh Agrawal

Reputation: 162

How to create an event with state update (by getDerivedStateFromProps)

I am trying to change componentWillReceiveProps method to static getDerivedStateFromProps and can't figure out how to use the keyword this inside the getDerivedStateFromProps function.

Originally, I wanted to use this.props.history.push() inside the getDerivedStateFromProps but could not figure out how.
I then tried returning state (as getDerivedStateFromProps is supposed to do) and could not create an event with it. A brief look at the code will make my question more comprehensible.

 static getDerivedStateFromProps(nextProps, prevState){
   if(nextProps.passwordResetResult.message==="Password reset 
      Successfully")
    {
      alert("Password reset successfully please login again");
         this.props.history.push('/home')
    }
   }

I know I am supposed to return state at the end; but I didn't find it useful for my purpose, as don't understand how do I create an event which will be triggered on state change after return and then trigger this.props.history.push().

Above code caused error

this.props is undefined.

I understand I can't use this keyword inside getDerivedStateFromProps; am I correct in assuming that?

Upvotes: 1

Views: 334

Answers (1)

Khaled Osman
Khaled Osman

Reputation: 1477

getDerviedStateFromProps is a static function, so you can't access this from it, static functions are bound to the class itself and not the instance of the component. I believe its intentionally done this way to avoid side effects.

So Instead of using this.history.push you should use nextProps.history.push which you get in the lifecycle hook arguments.

But as for your use-case since you said you don't really need to return state, it means you don't really need derived state because you don't change internal state based on specific props. You should use componentDidUpdate instead for side-effects, see https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

Upvotes: 1

Related Questions