1

In my code, I was using componentWillReceiveProps which I know has been deprecated, but my code seems to be working fine using that method. This is what I had:

componentWillReceiveProps(nextProps) {
    if(nextProps.tableData !== undefined) {
      const data = nextProps.tableData.datapaths.map(item => { return item.row });
      this.setState({ data });
    }
  }

Can someone tell me how can I apply the same logic to the method getDerivedStateFromProps because it doesn't like and complain when I tried using setState method inside this method:

static getDerivedStateFromProps(props, state) {
    if (props.tableData !== undefined) {
      const data = props.tableData.datapaths.map(item => { return item.row });
      state.data = data;
      this.setState({ data });
    }
  }
Shaun
  • 461
  • 5
  • 13
  • Does this answer your question? [How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps](https://stackoverflow.com/questions/49617486/how-to-use-lifecycle-method-getderivedstatefromprops-as-opposed-to-componentwill) – Taki Apr 11 '21 at 04:27
  • Thanks @Taki for sharing the link. I tried to follow the suggestions provided in that link but it still doesn't work for me. – Shaun Apr 11 '21 at 04:36

1 Answers1

1

you shouldn't setState inside getDerivedStateFromProps , just return the new state :

static getDerivedStateFromProps(props, state) {
  if (props.tableData !== undefined) {
    const data = props.tableData.datapaths.map(item => { return item.row });

    // this will update the state
    return { data };
  }
}
Taki
  • 17,320
  • 4
  • 26
  • 47