-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
100 lines (90 loc) · 2.64 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import * as React from 'react';
import { Controller, SubmitHandler, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { transformNumberOnChange, transformNumberValue } from './numberInputs';
const getSchema = (maxValue: number) => {
const validationSchema = z.object({
name: z.number().max(maxValue).nonnegative(),
});
return validationSchema;
};
type FormFieldType = z.infer<ReturnType<typeof getSchema>>;
export default function App() {
const [maxValue, setMaxValue] = React.useState(0);
const [maxValueLoading, setMaxValueLoading] = React.useState(false);
const validationSchema = getSchema(maxValue);
const {
handleSubmit,
control,
reset,
formState: { isSubmitting },
} = useForm<FormFieldType>({
mode: 'all',
resolver: zodResolver(validationSchema),
defaultValues: { name: undefined },
});
// mock api to get max value
React.useEffect(() => {
setMaxValueLoading(true);
setTimeout(() => {
setMaxValue(10);
setMaxValueLoading(false);
}, 2000);
}, []);
const onSubmit: SubmitHandler<FormFieldType> = async ({ name }) => {
console.log(name);
};
// if (maxValueLoading) {
// return (
// <React.Fragment>
// Max Value is loading for validation please wait.....
// </React.Fragment>
// );
// }
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="name"
render={({
field: { value, onChange, ...props },
fieldState: { error },
}) => {
return (
<React.Fragment>
{/* Number field */}
<input
type="number"
onChange={(e) => {
onChange(transformNumberOnChange(e));
}}
disabled={maxValueLoading}
value={transformNumberValue(value)}
{...props}
/>
{/* Error message */}
<p style={{ color: 'red', fontSize: '12px' }}>{error?.message}</p>
<p style={{ fontSize: '12px' }}>
{maxValueLoading && 'Max value loading..'}
</p>
</React.Fragment>
);
}}
/>
{/* Submit and Reset button */}
<div style={{ display: 'flex', gap: '8px' }}>
<button type="submit" disabled={maxValueLoading || isSubmitting}>
Submit
</button>
<button
type="button"
disabled={maxValueLoading}
onClick={() => reset()}
>
Reset
</button>
</div>
</form>
);
}