Skip to content

Commit

Permalink
feat: add watch to trigger hook
Browse files Browse the repository at this point in the history
  • Loading branch information
yoannfleurydev committed Sep 12, 2024
1 parent 2132e46 commit e0d31a2
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/lib/form/useWatchToTrigger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useEffect } from 'react';

import { FieldPath, FieldValues, UseFormReturn } from 'react-hook-form';

/**
* Use this hook to subscribe to fields and listen for changes to revalidate the
* form.
*
* Using the form "onBlur" validation will validate the field you just updated.
* But imagine a field that has to validate itself based on an another field update.
* That's the point of this hook.
*
* Example: imagine those fields: `min`, `default`, `max`. The `min` should be
* lower than the `default` and the `default` should lower than the `max`.
* `min` is equal to 2, `default` is equal to 4 and `max` is equal to 6.
* You update the `min` so the value is 5, the form (using superRefine and
* custom issues) will tell you that the `min` should be lower than the default.
* You update the `default` so the new value is 5.5. Without this hook, the
* field `min` will not revalidate. With this hook, if you gave the name, it will.
*/
export const useWatchToTrigger = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>(params: {
form: Pick<UseFormReturn<TFieldValues>, 'watch' | 'trigger'>;
names: Array<TName>;
}) => {
const { watch, trigger } = params.form;
useEffect(() => {
const subscription = watch((_, { name }) => {
if (name && params.names.includes(name as TName)) {
trigger(params.names);
}
});
return () => subscription.unsubscribe();
}, [watch, trigger, params.names]);
};

0 comments on commit e0d31a2

Please sign in to comment.