Skip to content

Commit

Permalink
fix(useformstate): fix race condition: only save validation if it's f…
Browse files Browse the repository at this point in the history
…rom the latest set of values (migtools#36)
  • Loading branch information
mturley authored Nov 5, 2020
1 parent 4d17462 commit 0bfc6ee
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/hooks/useFormState/useFormState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,25 @@ export const useFormState = <TFieldValues>(
const lastValuesRef = React.useRef(values);
React.useEffect(() => {
if (!hasRunInitialValidation || !equal(lastValuesRef.current, values)) {
lastValuesRef.current = values;
const schemaShape = fieldKeys.reduce(
(newObj, key) => ({ ...newObj, [key]: fields[key].schema }),
{} as { [key in keyof TFieldValues]?: yup.Schema<TFieldValues[key]> }
);
const schema = yup.object().shape(schemaShape).defined();
setHasRunInitialValidation(true);
lastValuesRef.current = values;
schema
.validate(values, { abortEarly: false, ...yupOptions })
.then(() => setValidationError(null))
.catch((e) => setValidationError(e as yup.ValidationError));
.then(() => {
if (lastValuesRef.current === values) {
setValidationError(null);
}
})
.catch((e) => {
if (lastValuesRef.current === values) {
setValidationError(e as yup.ValidationError);
}
});
}
}, [fieldKeys, fields, hasRunInitialValidation, validationError, values, yupOptions]);

Expand Down

0 comments on commit 0bfc6ee

Please sign in to comment.