react-final-formfinal-form

Final Form reset specific field value


I have two Field components, a Parent and a Child. As Child is dependant on the Parent, I want to reset Child whenever Parent is updated.

I tried this:

           <Field name="parent">
              {(props) => {
                return (
                  <Parent
                    onChange={(newValue) => {
                      props.input.onChange(newValue);
                      form.change('child', undefined);
                      form.resetFieldState('child');
                    }}
                    value={props.input.value}
                  />
                );
              }}
            </Field>
           <Field name="child">
              {(props) => {
                return (
                  <Child
                   value={props.input.value} // the value is not updated here,
                   onChange={props.input.onChange}
                  />
                );
              }}
            </Field>

but it does not seem to be working. What is the right way to do it?


Solution

  • You can achieve this using form decorator, for example, having a form with two fields firstName and lastName, to reset lastName whenever firstName is changed you could:

    <Form
          onSubmit={onSubmit}
          initialValues={{ stooge: "larry", employed: false }}
          decorators={[
            (formApi) => {
              let before = formApi.getState();
              const unsubscribe = formApi.subscribe(
                (state) => {
                  if (before.values.firstName !== state.values.firstName) {
                    formApi.change("lastName", "");
                  }
                  before = state;
                },
                { values: true }
              );
              return unsubscribe;
            }
          ]}>...</Form>
    

    in the example above, we subscribe for form state changes and compare the field value with the previous one, when it's changed, reset another one. Here is a codesandbox https://codesandbox.io/s/so-final-form-reset-specific-field-value-drvr4l?file=/index.js:593-619

    Oh, btw, there is ready-made package for this: https://github.com/final-form/final-form-calculate