Skip to content

Commit

Permalink
examples: restore state of form
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifumiSato committed Sep 3, 2022
1 parent 2e7ed66 commit 5fde768
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions examples/react-hook-form/pages/form/[index].tsx
@@ -1,20 +1,47 @@
import { 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 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 = {
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)

// form
const router = useRouter()
const { handleSubmit, register } = useForm<FormData>()
const onSubmit: SubmitHandler<FormData> = async data => {
const { handleSubmit, register } = useForm<FormData>({
mode: 'onBlur',
defaultValues: {
name,
comment,
},
})
const onSubmit: SubmitHandler<FormData> = async (data) => {
console.log('submit data', data)
await router.push('/form/success')
}
Expand All @@ -33,11 +60,19 @@ const Form: NextPage = () => {
<dl className={styles.formList}>
<dt>name</dt>
<dd>
<input type="text" {...register('name')} />
<input
type="text"
{...register('name')}
onChange={(e) => setName(e.target.value)}
/>
</dd>
<dt>comment</dt>
<dd>
<input type="text" {...register('comment')} />
<input
type="text"
{...register('comment')}
onChange={(e) => setComment(e.target.value)}
/>
</dd>
</dl>
<button>submit</button>
Expand Down

0 comments on commit 5fde768

Please sign in to comment.