Riya
Riya

Reputation: 89

Calling a asynchronous function inside getDerivedStateFromProps in React

I need to update a table when a state got updated. So I tried to call a function update inside getDerivedStateFromProps but it seems like I can't use 'this' inside getDerivedStateFromProps. Is there any way to do that? Thank in advance.

static getDerivedStateFromProps(props, state) {
    if(props.newValue != state.newValue) {
      this.updateTable();
      return {
        newValue : props.newValue 
      }
    }
    return null;
  }

Upvotes: 1

Views: 653

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

updateTable is a sideEffect function that need not be present in getDerivedStateFromProps

getDerivedStateFromProps is intentionally written as a static function so that you cannot call class instance functions from it

In order to handle sideEffect you must perform them in componentDidUpdate function

 componentDidUpdate(prevProps, prevState) {
    if(this.props.newValue != prevProps.newValue) {
      this.updateTable();
    }
  }

Upvotes: 2

Related Questions