Search code examples
reactjsformsreact-final-formfinal-form

How to get propperly FormState (dirtyFields, prestine, etc.) in handleSubmit function using React-Final-Form


Basically, I just want to get only that fields, that were changed (dirty). How should I get them inside submit handler? (I need to post only changed fields to API)

const handleSubmitSettings = (fields, formApi) => {
    console.log("Submitted with fields:", fields);
};

const handleValidate = (props) => {
    console.log("Validated with props:", props);
};

return (
    <Form
        onSubmit={handleSubmitSettings}
        validate={handleValidate}
    >
        {({handleSubmit,form: {submit, change}}) => (
                <form onSubmit={handleSubmit} className={classes.formFlexContainer}>
                    <SettingsHeader/>
                    <SettingsContainer/>
                </form>
        )}
    </Form>
);

Solution

  • In your submit handler you could retrieve all registered fields via the second argument formApi, then collect all fields marked dirty:

    const onSubmit = async (values, api) => {
      const dirtyOnly = {};
      for (let field of api.getRegisteredFields()) {
        const fs = api.getFieldState(field)
        if (fs.dirty) {
          dirtyOnly[fs.name] = fs.value;
        }
      }
      // submit dirtyOnly
    }
    
    

    in the example above, dirtyOnly object would contain all values from dirty fields. But such an approach seems questionable since it may not properly handle a case with more complex state shapes.