Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method inside getDerivedStateFromProps in React

Before upgrading react to version 16.3, I'd call a method based on changes in props like this :

componentWillReceiveProps(nextProps){
   if(this.props.country.length !== nextProps.country){
    doSomething(); //example calling redux action
    }
}

componentWillReceiveProps is unsafe on Version 16.3 and we must use getDerivedStateFromProps. However, this method returns an object and I don't know how I can call a method from inside it the same way I do with componentWillReceiveProps

like image 487
MBehtemam Avatar asked Apr 05 '18 05:04

MBehtemam


3 Answers

Yes, you need to return an object, which is the new state that that is derived from nextProp. According to docs:

getDerivedStateFromProps should return an object to update state, or null to indicate that the new props do not require any state updates.

But since you are not updating your state in any way inside your componentWillReceiveProps, you should use componentDidUpdate instead of getDerivedStateFromProps:

componentDidUpdate(prevProps){
  if ( prevProps.country !== this.props.country.length ) {
    doSomething(); //example calling redux action
  }
}
like image 200
Dane Avatar answered Oct 08 '22 13:10

Dane


For this situation, it was good for the OP to use componentDidUpdate but I found myself needing getDerivedStateFromProps so I had to make my custom function static as well and call it using the class' name inside getDerivedStateFromProps. Something like this:

componentDidMount() {
    const something = ClassComponentName.runThisFunction();
    this.setState({ updatedSomething: something });
}

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.key !== prevState.key) {
        return { 
            updatedSomething: ClassComponentName.runThisFunction()
        };
    }
    return null;
}

static runThisFunction() {
    //do stuff and return value
}

To clarify, this is updating the component's state on load as well as when new props arrive. This definitely took me back to my typed-language days. Hope it helps!

like image 41
Martavis P. Avatar answered Oct 08 '22 14:10

Martavis P.


if you need to call a function in "getDerivedStateFromProps", you can put this function in state in constructor , then get this function in "getDerivedStateFromProps" from state.

put function in state in constructor:

constructor(props){
   super(props);
   this.state = {
      func1:this.func1.bind(this)
   }
}

get function from state in getDerivedStateFromProps:

getDerivedStateFromProps(props,state){
   return {
       model:state.func1(props.model)
   }
}
like image 22
mohammad feiz Avatar answered Oct 08 '22 14:10

mohammad feiz