Last active
May 5, 2023 07:00
-
-
Save devgioele/46784cd2f6a4068b3799e488284f8a98 to your computer and use it in GitHub Desktop.
An extension of react-hook-form's `useFormContext`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash' | |
import { useRef } from 'react' | |
import { | |
FieldError, | |
FieldPath, | |
FieldValues, | |
useFormContext, | |
} from 'react-hook-form' | |
import { DistributivePick } from '../typescript/DistributivePick' | |
export type FieldState = { | |
invalid: boolean | |
isDirty: boolean | |
isTouched: boolean | |
error?: FieldError | |
} | |
export const useAugmentedFormContext = <TFieldValues extends FieldValues>() => { | |
const methods = useFormContext<TFieldValues>() | |
const dirtyRegistryRef = useRef<Record<string, boolean | undefined>>({}) | |
const getValues = <TFieldName extends FieldPath<TFieldValues>>( | |
names: TFieldName[] | |
) => { | |
const values = methods.getValues(names) | |
const obj = _.zipObject(names, values) | |
return obj as DistributivePick<TFieldValues, TFieldName> | |
} | |
const getFieldStates = <TFieldName extends FieldPath<TFieldValues>>( | |
names: TFieldName[] | |
) => { | |
const fieldStates = {} as Record<TFieldName, FieldState> | |
for (const name of names) { | |
fieldStates[name] = methods.getFieldState(name) | |
} | |
return fieldStates | |
} | |
const isOrWasDirty = <TFieldName extends FieldPath<TFieldValues>>( | |
name: TFieldName | |
) => { | |
const { isDirty } = methods.getFieldState(name) | |
if (isDirty) { | |
dirtyRegistryRef.current[name] = true | |
} | |
return dirtyRegistryRef.current[name] ?? false | |
} | |
const isOrWasAtLeastOneDirty = <TFieldName extends FieldPath<TFieldValues>>( | |
names: TFieldName[] | |
) => { | |
const dirtyValues = names.map((name) => isOrWasDirty(name)) | |
return dirtyValues.some((dirty) => dirty) | |
} | |
return { | |
...methods, | |
getValues, | |
getFieldStates, | |
isOrWasDirty, | |
isOrWasAtLeastOneDirty, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One may also avoid importing lodash by using: