Siva
Siva

Reputation: 101

How to move away from componentWillReceiveProps

As componentWillReceiveProps is deprecated, how do we migrate the below code?

componentWillReceiveProps (nextProps) {
  if (nextProps.reloadData && nextProps.realoadDataId) {
    this.props.onChange({
      target: { id: 'reloadData', value: false }
    })
    this.props.reloadData();
  }

  if (this.props.dataUpdated) {
    this.setState({
      sucessMessage: 'Updated Successfully'
    })
  }
 
  if (nextProps.error) {
    this.props.setToast(nextProps.error, true)
  }

  if (nextProps.downloadDataList && nextProps.downloadDataList.length > 0) {
    downloadDataAsExcel(nextProps.downloadDataList);
    this.props.onChange({
      target: { id: 'downloadDataList', value: null }
    })
  }
}

Upvotes: 1

Views: 34

Answers (1)

Gavara.Suneel
Gavara.Suneel

Reputation: 616

You can use static getDerivedStateFromProps(nextProps, prevState) method to replicate the above behaviour.

    static getDerivedStateFromProps(nextProps, prevState) {
            if (nextProps.reloadData && nextProps.realoadDataId) {
                nextProps.props.onChange({target: {id: 'reloadData', value: false}})
                nextProps.props.reloadData();
            }
    
            if (nextProps.error) {
                nextProps.setToast(nextProps.error, true)
            }
            
if (nextProps.downloadDataList && nextProps.downloadDataList.length > 0
         {
             downloadDataAsExcel(nextProps.downloadDataList);
                nextProps.onChange({target: {id: 'downloadDataList', value: null}})
    
      }
if (nextProps.dataUpdated) {
                return {
                     sucessMessage: 'Updated Successfully'
                 }
            } 
return null;

}

You can use the return statement to get the state based on the incoming props.

Upvotes: 2

Related Questions