What do you do for clearing useActionState
/useFormState
errors on typing?
#66424
Unanswered
vadimshvetsov
asked this question in
App Router
Replies: 1 comment
-
Code above is not fully solving the good UX problem for me. There are cases when previous error message is shown for several ms until new error message will come and replace it. I didn't find a good way how to fix it with maintaining Finally I've ended up with this approach. It helps to control and clear error message when needed (ex: when form is submitting). function useFieldError(
name: string,
error: string | undefined,
): {
fieldError: string
onChange: ChangeEventHandler
} {
const { data, pending } = useFormStatus()
const [prevValue, setPrevValue] = useState<string>()
const [fieldError, setFieldError] = useState<string>(error ?? "")
useEffect(() => {
const value = data && data.get(name)
if (value && typeof value === "string") {
setPrevValue(value)
}
}, [data])
useEffect(() => {
if (pending) {
setFieldError("")
}
}, [pending])
useEffect(() => {
if (error) {
setFieldError(error)
}
// Error message might the same as previous one
}, [data, error])
function onChange(e: ChangeEvent<HTMLInputElement>): void {
const { value } = e.target
if (value === prevValue) {
setFieldError(error ?? "")
return
}
setFieldError("")
}
return { fieldError, onChange }
}
export function EmailField({
error,
...props
}: { error?: string } & Partial<Parameters<typeof Input>[0]>) {
const { pending } = useFormStatus()
const { fieldError, onChange } = useFieldError("email", error)
return (
<>
<Input
name="email"
placeholder="Email"
type="email"
disabled={pending}
required
className={cn({ ["border-destructive"]: fieldError })}
onChange={onChange}
{...props}
/>
{fieldError && <Typography variant="error">{fieldError}</Typography>}
</>
)
} Apreciate your ideas how to do it in a better way. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I was wondering if there is a recipe of clearing error messages from server actions on typing.
There is a short overview of current behaviour:
Action
Form
So when I submit form with


asd@asd.asd
email which doesn't pass validation I see the error:And when I changing email I still see the error for the last submission which is expected.
I want to clear this error message when I'm changing the form. So I didn't find the better way yet then just to add custom
useFieldState
hook but I'm still looking for better solution.Form
What do you think?
Beta Was this translation helpful? Give feedback.
All reactions