feat: trigger validation on form upon autofill in enter details * feat: trigger validation on form upon autofill in enter details Approved-by: Niclas Edenvin
32 lines
830 B
TypeScript
32 lines
830 B
TypeScript
"use client"
|
|
import { useEffect } from "react"
|
|
import { useFormContext } from "react-hook-form"
|
|
|
|
export default function AutoFillDetector() {
|
|
const {
|
|
formState: { dirtyFields, isDirty, touchedFields },
|
|
trigger,
|
|
watch,
|
|
} = useFormContext()
|
|
|
|
useEffect(() => {
|
|
const dirtyFieldKeys = Object.keys(dirtyFields)
|
|
const touchedFieldKeys = Object.keys(touchedFields)
|
|
const hasDirtyUnTouchedFields = dirtyFieldKeys.some(
|
|
(field) => !touchedFieldKeys.includes(field)
|
|
)
|
|
const subscription = watch((_, field) => {
|
|
if (!field.type) {
|
|
if (isDirty && hasDirtyUnTouchedFields) {
|
|
trigger(field.name)
|
|
trigger("countryCode")
|
|
}
|
|
}
|
|
})
|
|
|
|
return () => subscription.unsubscribe()
|
|
}, [dirtyFields, isDirty, touchedFields, trigger, watch])
|
|
|
|
return null
|
|
}
|