final-form / final-form-set-field-data

Mutator for setting arbitrary metadata on fields in 🏁 Final Form

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Best Practices for Warnings in Validate?

shrugs opened this issue · comments

Are there any known best practices for setting field warnings (using field data) within the validate or submit functions? In our case the warnings can only be generated after the lengthy 'validate' or 'submit' process, which we obviously want to run as infrequently as possible.

When setting warnings in the validate function, a render loop is triggered since calling a mutator automatically triggers re-validation [FinalForm.js#L268](https://github.com/final-form/final-form/blob/master/src/FinalForm.js#L268]

The only examples I find are doing warnings out-of-band, most likely to avoid this issue, but then we'd be running our validation function twice, and that's a hard pill to swallow.


my solution right now is something like

const warnings = useRef({});

const validate = useCallback((values) => {
  warnings.current.myField = null;
}, []);

const onSubmit = useCallback(
  async values => {
      // ... some long-running submit function...
      // notify the user, but allow login regardless
      if (noPermissions) {
        warnings.current.myField =
          'some sort of warning';
      }
  },
  []
);


return (
     <Input ...>
     {warnings.current.myField && (
        <Flex.Item as={ErrorText} className="mv1">
          {warnings.current.myField}
        </Flex.Item>
      )}
);

but I feel iffy about using the ref, but it's a happy accident that the form is always re-rendered after validation/submit, so the ref value is always shown correctly (in this specific case)