Search code examples
reactjsreact-final-formfinal-form

How to subscribe to field changes only after the form has been initialized in react-final-form


I have a react-final-form form, which needs to be initialized from the state. When one of the fields changes I want to reset the form to initial (empty) values. So I use subscription to the field's dirty state and if it changes I use OnChange to reset the form:

<Field name="option" subscription={{ dirty: true }}>
  {({ input: { onChange } }) => (
    <OnChange name="option">
      {value => {
        form.reset({
          ...initialValues,
          option: value
        });
      }}
    </OnChange>
  )}
</Field>

But it doesn't work, as the form gets reset immediately after it has been initialized. Is there any way to separate these two events? So that I could reset the form only if its field has been modified by the user?

Here is the link to my codesandbox.


Solution

  • It doesn't work because <Field /> component will need to be rendered at least first time because its purpose is to rendering field UI not to hook callback. I'd suggest you to use <FormSpy /> instead because it intend for hooking callback even though it might hard for specific field

     <FormSpy
        subscription={{ dirtyFields: true }}
        onChange={props => {
            if (props.dirtyFields.option) {
            form.reset({
                ...initialValues,
                option:
                form.getFieldState("option") &&
                form.getFieldState("option").value
            });
            }
        }}
    />
    

    codesandbox

    FormSpy