Search code examples
reactjsreact-18react-lifecycle-hookscomponentwillreceiveprops

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}})
        }
}

Thanks in advance


Solution

  • 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.