Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Zod]: Resolver does not validate to reflect correct error state without manual form.trigger() #671

Open
MusaGillani opened this issue Mar 22, 2024 · 9 comments

Comments

@MusaGillani
Copy link

Describe the bug
Form Validation doesn't re render the correct error message to reflect correct error from formState

To Reproduce
Steps to reproduce the behavior:

  1. Visit the sandbox with a minimal working example using react-hook-form bootstrapped with shadcn ui
  2. Enter a value smaller than the total value listed in UI in the Base labelled input field
  3. Click submit
  4. The error message indicates a sum mismatch
  5. Enter the remaining sum value in any other field
  6. This does not cause the error message to hide although the error state updates correctly, verified from console logs
  7. Only changing the values in Base input field remove the errors from the UI

Screen recording showing validation not running:
Video

Sandbox link

Expected behavior
Validation should trigger when changing a any other field than base ,
due to formState update causing resolver to re-validate the form data

Desktop:

  • OS: Mac OS
  • Browser: chrome
  • Version 122

Additional context
The error is fixed using form.trigger() directly in the onChange of the <Input/> component, which removes the error from the UI when changing the input value.
Maybe the formState is being updated correctly but the resolver does cause a re-render?

Screen Recording, showing form.trigger() added to the Overtime label triggers the validation
Video

@briavicenti
Copy link

We're having a similar issue, described in a comment here! I think that these two issues are dupes.

@sowka1995
Copy link

I have a similar issue. The refine function is triggered and resolved but error from formState.erros does not disappear -> if I call form.trigger() in every onChange field callback then everything works good and errors are cleared form formState.

@sowka1995
Copy link

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

@MusaGillani
Copy link
Author

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting,
could you point me to some docs for this? would like to dig a lil deeper

@sowka1995
Copy link

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

@MusaGillani
Copy link
Author

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

@sowka1995
Copy link

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

Maybe, but I do not think so. The problem with using trigger() is that in the case of mode="onSubmit" (default) the error will be displayed even before the form is submitted but using rules.deps, the error appears only after submit.

@MusaGillani
Copy link
Author

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

Maybe, but I do not think so. The problem with using trigger() is that in the case of mode="onSubmit" (default) the error will be displayed even before the form is submitted but using rules.deps, the error appears only after submit.

yeah we're using submitCount from formState to only trigger() when the form is submitted once.
since the entire schema needs to be validated all trigger() calls we're already running in a useEffect using watch()'s subscription. just added that check in useEffect

here's the snippet for that

  useEffect(() => {
    if (form.formState.submitCount === 0) {
      return;
    }
    const subscription = form.watch(() => form.trigger());
    return () => subscription.unsubscribe();
  }, [form.watch, form.trigger, form.formState, form]);

@benjamin-andersen
Copy link

benjamin-andersen commented Sep 18, 2024

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D
https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

Maybe, but I do not think so. The problem with using trigger() is that in the case of mode="onSubmit" (default) the error will be displayed even before the form is submitted but using rules.deps, the error appears only after submit.

yeah we're using submitCount from formState to only trigger() when the form is submitted once. since the entire schema needs to be validated all trigger() calls we're already running in a useEffect using watch()'s subscription. just added that check in useEffect

here's the snippet for that

  useEffect(() => {
    if (form.formState.submitCount === 0) {
      return;
    }
    const subscription = form.watch(() => form.trigger());
    return () => subscription.unsubscribe();
  }, [form.watch, form.trigger, form.formState, form]);

Thanks for the workaround! I was searching for a long time to find a solution to this issue...

If anyone happens to want to trigger the revalidation with a different validation strategy (e.g. "onBlur" instead of the default "onSubmit"), you can try this:

Note: I have not really fully tested this, seems fine at a glance. Use at your own risk :)
Also note: This will also of course cause an extra re-render, so maybe someone else can come up with a more optimal workaround that handles it for other validation strategies.

const [hasValidated, setHasValidated] = useState(false)

// hack to enable form revalidation
// only after form has been validated for the first time
useEffect(() => {
    if (hasValidated) return
    if (!form.formState.isValidating) return
    setHasValidated(true)
}, [form.formState.isValidating, hasValidated])

// manually trigger entire form revalidation
// anytime any of the form values changes
useEffect(() => {
    if (!hasValidated) return

    const subscription = form.watch(() => form.trigger())
    return subscription.unsubscribe
}, [form.watch, form.trigger, hasValidated])

And here is a wrapper on-top of useForm with this functionality built-in:

// useFormWithRevalidate.ts
import {useEffect, useState} from 'react'
import {
    FieldValues,
    UseFormProps,
    UseFormReturn,
    useForm,
} from 'react-hook-form'

/**
 * This is a wrapper of {@link useForm}.
 *
 * It is a workaround for a bug with react-hook-form   zod resolver.
 *
 * See details: https://github.com/react-hook-form/resolvers/issues/671
 */
export const useFormWithRevalidate = <
    TFieldValues extends FieldValues = FieldValues,
    TContext = any,
    TTransformedValues extends FieldValues | undefined = undefined,
>(
    props?: UseFormProps<TFieldValues, TContext>,
): UseFormReturn<TFieldValues, TContext, TTransformedValues> => {
    const form = useForm<TFieldValues, TContext, TTransformedValues>(props)
    const [hasValidated, setHasValidated] = useState(false)

    // hack to enable form revalidation
    // only after form has been validated for the first time
    useEffect(() => {
        if (hasValidated) return
        if (!form.formState.isValidating) return
        setHasValidated(true)
    }, [form.formState.isValidating, hasValidated])

    // manually trigger entire form revalidation
    // anytime any of the form values changes
    useEffect(() => {
        if (!hasValidated) return

        const subscription = form.watch(() => form.trigger())
        return subscription.unsubscribe
    }, [form.watch, form.trigger, hasValidated])

    return form
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants