2022-09-21 09:38:57 +02:00
|
|
|
import { Form, useForm } from 'react-component-form'
|
|
|
|
import type { HandleUseFormCallback } from 'react-component-form'
|
2022-08-26 20:19:31 +02:00
|
|
|
import useTranslation from 'next-translate/useTranslation'
|
|
|
|
|
|
|
|
import { Input } from './design/Input'
|
|
|
|
import { Button } from './design/Button'
|
|
|
|
import { useFormTranslation } from '../hooks/useFormTranslation'
|
|
|
|
import { userSchema } from '../models/User'
|
|
|
|
import { FormState } from './design/FormState'
|
|
|
|
|
2022-08-26 22:53:59 +02:00
|
|
|
const simulateServerRequest = async (ms: number): Promise<void> => {
|
2022-08-26 20:19:31 +02:00
|
|
|
return await new Promise((resolve) => {
|
|
|
|
setTimeout(resolve, ms)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export const FormExample: React.FC = () => {
|
|
|
|
const { handleUseForm, errors, fetchState, message } = useForm(userSchema)
|
|
|
|
const { getFirstErrorTranslation } = useFormTranslation()
|
|
|
|
const { t } = useTranslation()
|
|
|
|
|
|
|
|
const onSubmit: HandleUseFormCallback<typeof userSchema> = async (
|
|
|
|
formData,
|
|
|
|
formElement
|
|
|
|
) => {
|
2023-04-02 22:08:32 +02:00
|
|
|
await simulateServerRequest(2_000)
|
2022-08-26 20:19:31 +02:00
|
|
|
console.log('onSubmit:', formData)
|
|
|
|
formElement.reset()
|
|
|
|
return {
|
|
|
|
type: 'success',
|
2023-04-02 22:08:32 +02:00
|
|
|
message: 'common:success-message'
|
2022-08-26 20:19:31 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<section>
|
|
|
|
<Form
|
|
|
|
className='mt-6 w-[90%] max-w-xs'
|
|
|
|
noValidate
|
|
|
|
onSubmit={handleUseForm(onSubmit)}
|
|
|
|
>
|
|
|
|
<Input
|
|
|
|
type='text'
|
|
|
|
placeholder={t('common:name')}
|
|
|
|
name='name'
|
|
|
|
label={t('common:name')}
|
|
|
|
error={getFirstErrorTranslation(errors.name)}
|
|
|
|
/>
|
|
|
|
|
|
|
|
<Input
|
|
|
|
type='text'
|
|
|
|
placeholder='Email'
|
|
|
|
name='email'
|
|
|
|
label='Email'
|
|
|
|
error={getFirstErrorTranslation(errors.email)}
|
|
|
|
/>
|
|
|
|
|
2022-08-26 23:47:48 +02:00
|
|
|
<Button className='mt-6 w-full' type='submit' data-cy='submit'>
|
2022-08-26 20:19:31 +02:00
|
|
|
Submit
|
|
|
|
</Button>
|
|
|
|
</Form>
|
2022-08-26 22:53:59 +02:00
|
|
|
|
|
|
|
<FormState
|
|
|
|
id='message'
|
|
|
|
state={fetchState}
|
|
|
|
message={message != null ? t(message) : undefined}
|
|
|
|
/>
|
2022-08-26 20:19:31 +02:00
|
|
|
</section>
|
|
|
|
)
|
|
|
|
}
|