Skip to content

Commit

Permalink
examples: refactor reac-hook-form
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifumiSato committed Sep 4, 2022
1 parent b16fdef commit 0d9c56e
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions examples/react-hook-form/src/hooks/useFormSync.ts
Expand Up @@ -14,25 +14,26 @@ import {
} from 'recoil'

type UseFormSyncReturn<
TFieldValues extends FieldValues = FieldValues,
TFieldValues extends FieldValues,
TContext = any
> = UseFormReturn<TFieldValues, TContext> & { onChangeForm: () => void }

export function useFormSync<
TFieldValues extends FieldValues = FieldValues,
TContext = any
>(
export function useFormSync<TFieldValues extends FieldValues, TContext = any>(
formState: RecoilState<TFieldValues>,
props?: Omit<UseFormProps<TFieldValues, TContext>, 'defaultValues'>
): UseFormSyncReturn<TFieldValues> {
): UseFormSyncReturn<TFieldValues, TContext> {
const getDefaultValues = useRecoilCallback(
({ snapshot }) =>
() => {
return snapshot.getLoadable(formState).contents
const formLoadable = snapshot.getLoadable(formState)
if (formLoadable.state === 'hasValue') {

This comment has been minimized.

Copy link
@koichik

koichik Sep 4, 2022

Member

Good catch! however I prefer to reverse the conditions (early exit).

return formLoadable.contents
}
throw new Error('useFormSync: not support async state.')
},
[]
)
const defaultValuesRef = useRef<DeepPartial<TFieldValues>>()
const defaultValuesRef = useRef<TFieldValues>()
defaultValuesRef.current ??= getDefaultValues()

const {
Expand All @@ -41,7 +42,9 @@ export function useFormSync<
...rest
} = useForm<TFieldValues, TContext>({
...props,
defaultValues: defaultValuesRef.current,
// `DeepPartial` is expected to be removed in the future
// https://github.com/react-hook-form/react-hook-form/issues/8510#issuecomment-1157129666
defaultValues: defaultValuesRef.current as DeepPartial<TFieldValues>,
})

const setFormValues = useSetRecoilState(formState)
Expand Down

0 comments on commit 0d9c56e

Please sign in to comment.