react-final-form input.onChange(null) does not update state immediately

621 Views Asked by At

We currently have a component <RenderDropdown /> which renders a material-ui <Select /> element. This takes options as props and is wrapped in a react-final-form <Field />.

Our issue is when we load the initialValues props of the <Form />, there are a few cases where the selected dropdown value no longer exists in the dropdown, so we want to set the dropdown value to null. We do that within the <RenderDropdown />:

  componentDidMount() {
    this.clearInputIfValueDoesntExistInOptions();
  }

  componentDidUpdate() {
    this.clearInputIfValueDoesntExistInOptions();
  }

 clearInputIfValueDoesntExistInOptions() {
    const {
      input: { value, onChange },
      options
    } = this.props;

    // Clear input value if it doen't exist in options
    if (
      value &&
      !options.some((option) => option.key === value || option.value === value)
    ) {
      console.log(
        "clearInputIfValueDoesntExistInOptions",
        "Setting value to null as the selected value does not exist in the current dropdown's options"
      );
      // If I use input.onChange, it does not update the final form state to null immediately.
      onChange(null);
    }
  }

This does set the value to null, but the form state does not update immediately, so the UI does not update either. It only updates once we change another field value or if we submit the form.

I've made a quick demo that simulates our issue: https://codesandbox.io/s/react-final-form-inputonchange-null-k7poj

Thanks.

0

There are 0 best solutions below