Skip to content

Commit

Permalink
examples: react-hook-form imporved render call
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifumiSato committed Sep 4, 2022
1 parent 5fde768 commit b16fdef
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 40 deletions.
65 changes: 25 additions & 40 deletions examples/react-hook-form/pages/form/[index].tsx
@@ -1,47 +1,40 @@
import { string } from '@recoiljs/refine'
import { object, string } from '@recoiljs/refine'
import Head from 'next/head'
import { useRouter } from 'next/router'
import { useForm } from 'react-hook-form'
import { SubmitHandler } from 'react-hook-form/dist/types/form'
import { atom, useRecoilState } from 'recoil'
import { syncEffect } from 'recoil-sync'
import { initializableAtom } from 'recoil-sync-next'
import { useFormSync } from '../../src/hooks/useFormSync'
import styles from '../../styles/form.module.css'

import type { NextPage } from 'next'

const nameState = atom({
key: 'nameState',
default: '',
effects: [syncEffect({ refine: string() })],
})

const commentState = atom({
key: 'commentState',
default: '',
effects: [syncEffect({ refine: string() })],
})

type FormData = {
type FormState = {
name: string
comment: string
}

const formState = initializableAtom<FormState>({
key: 'formState',
effects: [
syncEffect({
refine: object({
name: string(),
comment: string(),
}),
}),
],
})

const Form: NextPage = () => {
// Every time recoil state is updated, rendering is called,
// but no DOM update is made if it is kept to un-controlling components.
const [name, setName] = useRecoilState(nameState)
const [comment, setComment] = useRecoilState(commentState)
// check render
console.log('Form: re render')

// form
const { register, onChangeForm, handleSubmit } = useFormSync(
formState({ name: 'a', comment: 'b' })
)
const router = useRouter()
const { handleSubmit, register } = useForm<FormData>({
mode: 'onBlur',
defaultValues: {
name,
comment,
},
})
const onSubmit: SubmitHandler<FormData> = async (data) => {
const onSubmit: SubmitHandler<FormState> = async (data) => {
console.log('submit data', data)
await router.push('/form/success')
}
Expand All @@ -56,23 +49,15 @@ const Form: NextPage = () => {
<main className={styles.main}>
<h1 className={styles.title}>Form</h1>

<form onSubmit={handleSubmit(onSubmit)}>
<form onSubmit={handleSubmit(onSubmit)} onChange={onChangeForm}>
<dl className={styles.formList}>
<dt>name</dt>
<dd>
<input
type="text"
{...register('name')}
onChange={(e) => setName(e.target.value)}
/>
<input type="text" {...register('name')} />
</dd>
<dt>comment</dt>
<dd>
<input
type="text"
{...register('comment')}
onChange={(e) => setComment(e.target.value)}
/>
<input type="text" {...register('comment')} />
</dd>
</dl>
<button>submit</button>
Expand Down
59 changes: 59 additions & 0 deletions examples/react-hook-form/src/hooks/useFormSync.ts
@@ -0,0 +1,59 @@
import { useCallback, useRef } from 'react'
import {
DeepPartial,
FieldValues,
useForm,
UseFormProps,
UseFormReturn,
} from 'react-hook-form'
import {
RecoilState,
useRecoilCallback,
useResetRecoilState,
useSetRecoilState,
} from 'recoil'

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

export function useFormSync<
TFieldValues extends FieldValues = FieldValues,
TContext = any
>(
formState: RecoilState<TFieldValues>,
props?: Omit<UseFormProps<TFieldValues, TContext>, 'defaultValues'>
): UseFormSyncReturn<TFieldValues> {
const getDefaultValues = useRecoilCallback(
({ snapshot }) =>
() => {
return snapshot.getLoadable(formState).contents
},
[]
)
const defaultValuesRef = useRef<DeepPartial<TFieldValues>>()
defaultValuesRef.current ??= getDefaultValues()

const {
getValues,
reset: resetForm,
...rest
} = useForm<TFieldValues, TContext>({
...props,
defaultValues: defaultValuesRef.current,
})

const setFormValues = useSetRecoilState(formState)
const onChangeForm = useCallback(() => {
setFormValues(getValues())
}, [setFormValues, getValues])

const resetState = useResetRecoilState(formState)
const reset = useCallback(() => {
resetState()
resetForm(getDefaultValues())
}, [getDefaultValues, resetForm, resetState])

return { ...rest, getValues, reset, onChangeForm }
}

0 comments on commit b16fdef

Please sign in to comment.