Search code examples
reactjsreact-propscomponentwillreceiveprops

Updating props doesn't invoke componentWillReceiveProps method


In the UI I have two buttons, addRow & removeRow. AddRow adds a new row with dropdowns and removeRow removes them. For some reason, the clicking the remove row doesn't removes the row from the UI. The parent class is a functional component:

export const LimitUpdateSRCreate: React.FC<Props> = (props) => {
  const [defaultCategory, setDefaultCategory] = React.useState<string>(
    undefined
  );
  const [defaultResource, setDefaultResource] = React.useState<string>(
    undefined
  );
  const [limitFields, setLimitFields] = React.useState<ResourceLimitFields[]>(
    []
  );
 const [resourceInputRows, setResourceInputRows] = React.useState<
    ResourceInputRow[]
  >([]);

  return (
    <LimitRequestInputList
            serviceCategoryTestId="sr-service-select-id"
            resourceTestId="sr-resource-select-id"
            defaultCategory={defaultCategory}
            defaultResource={defaultResource}
            setGeneratedFields={setLimitFields}
            setResourceLimitRows={setResourceInputRows}
            rows={resourceInputRows}
            generatedFields={limitFields}
            incidentTypes={
              !!incidentTypes.response ? incidentTypes.response.data : []
            }
          />
  )
};

The LimitRequestInputList component is a class component, which has the addRow & removeRow buttons:

export class LimitRequestInputList extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      nextId : 0
    };
  }

  public componentDidMount(): void {
    this.createDefaultRow(this.props);
  }
  private createDefaultRow(otherProps: Props): void {
    if (otherProps && otherProps.incidentTypes && otherProps.incidentTypes.length && !otherProps.rows.length) {
      const firstId = 0;
      const defaultRow = [
        { id: firstId, 
          row: (
            <ResourceLimitIncreaseRow
              serviceCategoryTestId={otherProps.serviceCategoryTestId}
              resourceTestId={otherProps.resourceTestId}
              rowId={firstId}
              key={"" + firstId}
              isDefaultRow={true}
              defaultCategory={otherProps.defaultCategory}
              defaultResource={otherProps.defaultResource}
              setGeneratedFields={this.setGeneratedFields}
              formRef={otherProps.formRef}
              incidentTypes={otherProps.incidentTypes}
              removeRow={this.removeRow}
            />)
        }];
      this.addGeneratedFields(firstId);
      this.setState ({
        nextId : firstId + 1
      });
      this.props.setResourceLimitRows(defaultRow);
    }
  }

  public componentWillReceiveProps(nextProps: Props): void {
    this.createDefaultRow(nextProps);
    
  }
private addRow = (): void => {
    const newNextId = this.state.nextId + 1;
    const currentRows = this.props.rows;
    currentRows.push({ id: this.state.nextId, row: (
    <ResourceLimitIncreaseRow
      serviceCategoryTestId={this.props.serviceCategoryTestId}
      resourceTestId={this.props.resourceTestId}
      key={"" + this.state.nextId}
      rowId={this.state.nextId}
      isDefaultRow={false}
      setGeneratedFields={this.setGeneratedFields}
      formRef={this.props.formRef}
      incidentTypes={this.props.incidentTypes}
      removeRow={this.removeRow}
    />
    )});
    this.addGeneratedFields(this.state.nextId);
    this.setState({ nextId: newNextId });
    this.props.setResourceLimitRows(currentRows);
  }

  private removeRow = (rowId: number): void => {
    const rows = this.props.rows;
    const currentRow = rows ? rows.findIndex(row => row.id === rowId) : -1;
    if (currentRow !== -1) {
      rows.splice(currentRow, 1);
      this.props.setResourceLimitRows(rows);
    }
    this.removeGeneratedFields(rowId);
  }

  private addGeneratedFields = (rowId: number): void => {
    const newGeneratedFieldsRow: ResourceLimitFields = {
      id: rowId,
      serviceCategoryFieldName: ServiceCategoryFieldName + rowId,
      resourceFieldName: ResourceFieldName + rowId,
      generatedFields: []
    };
    const newGeneratedFields = this.props.generatedFields;
    newGeneratedFields.push(newGeneratedFieldsRow);
    this.props.setGeneratedFields(newGeneratedFields);
  }

  private removeGeneratedFields = (rowId: number): void => {
    const generatedFieldRows = this.props.generatedFields;
    const currentRow = generatedFieldRows ? generatedFieldRows.findIndex(row => row.id === rowId) : -1;
    if (currentRow !== -1) {
      generatedFieldRows.splice(currentRow, 1);
      this.props.setGeneratedFields(generatedFieldRows);
    }
  }

  private getResourceRows = (): JSX.Element[] => {
    const resourceRows : JSX.Element[] = this.props.rows.map(resourceRow => resourceRow.row);
    return resourceRows;
  }

  private setGeneratedFields = (resourceLimitFields: ResourceLimitFields) : void => {
    const generatedFieldRows = this.props.generatedFields;
    const currentRowIndex = generatedFieldRows ? 
    generatedFieldRows.findIndex(row => row.id === resourceLimitFields.id) : -1;
    if (currentRowIndex === -1) {
      generatedFieldRows.push(resourceLimitFields);
    } else {
      generatedFieldRows[currentRowIndex].generatedFields = resourceLimitFields.generatedFields;
    }
    this.props.setGeneratedFields(generatedFieldRows);
  }
}

As far as I know, whenever there is a change in the props, the componentWillReceiveProps methods gets invoked. In my code thats not happening. Is the issue because the parent is a functional component & the child is a class component. I guess it shouldn't be a case. Because of this, clicking the remove button doesn't removes the row from the UI. What could be the reason that the componentWillReceiveProps doesn't get invoked? I made sure that the props value is different everytime the button is clicked.


Solution

  • You're mutating the rows prop in the remove method, better remove it by using filter:

    private removeRow = (rowId: number): void => {
        const rows = this.props.rows.filter(r => r.id !== rowId);
    
        this.props.setResourceLimitRows(rows);
    
        this.removeGeneratedFields(rowId);
     }
    

    When you do const rows = this.props.rows; the new rows variable still points to the this.props.rows and all the changes to it are reflected on this.props.rows.

    Another way would be to make a shallow copy of props array via const rows = this.props.rows.concat() or const rows = this.props.rows.slice() before modifying rows.