1

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.

Valchy
  • 165
  • 3
  • 14

1 Answers1

2

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 }
}
mikheevm
  • 559
  • 5
  • 14
  • What if the method I want to call is triggered by an onClick event. I can't just tell react to update... – Valchy May 04 '19 at 10:18
  • 1
    Sorry, I don't get how the onClick event is connected with `getDerivedStateFromProps`. Do you mind sharing the code or giving some more detailed explanation of what you're trying to achieve? – mikheevm May 04 '19 at 10:20
  • 1
    You know what it took me a 300-word comment, I was just about to post it, explaining exactly why I need to call a method in `getDerivedStateFromProps` when it hit me, IT DOESN'T. XD ^_^. I figured it out so thanks :DD – Valchy May 04 '19 at 10:30