Search code examples
javascriptreactjsgetderivedstatefromprops

How to call a method inside getDerivedStateFromProps in ReactJS?


I have a method inside my React class e.g. someMethod(). I also have a getDerivedStateFromProps() method in which I want to call someMethod(). Yes I need to do this in getDerivedStateFromProps and not in componentDidUpdate() for example because I do change the state in someMethod().

someMethod() {
    this.setState({worked: true});
    return 'worked';
}

static getDerivedStateFromProps(props, state) {
    console.log(someMethod());
}

I would like for the log of worked to be displayed.


Solution

  • In getDerivedStateFromProps you don't have an access to the component's instance. So, basically, you can't. But what you can do is return an object to update the state.

    static getDerivedStateFromProps(props, state) {
        return { worked: true }
    }