@@ -18,63 +18,34 @@ type ErrorsState = Partial<{
1818} >
1919
2020export const ReactForm : FC = ( ) => {
21- const [ errors , setErrors ] = useState < ErrorsState > ( )
21+ const [ errors , setErrors ] = useState < ErrorsState | null > ( null )
2222
2323 const [ optimisticState , addOptimisticState ] = useOptimistic < string [ ] > ( [ ] )
2424
25- const handleFormSubmit = async ( previousState : FormSchema , formData : FormData ) => {
25+ const handleFormSubmit = async ( previousState : string , formData : FormData ) => {
2626 try {
27+ setErrors ( null )
28+
2729 addOptimisticState ( [ 'Submitting form...' ] )
2830
2931 const formDataEntries = Object . fromEntries ( formData . entries ( ) )
3032 const result = formSchema . safeParse ( formDataEntries )
3133
3234 if ( result . error ) {
33- addOptimisticState ( [ 'Form submission failed!' ] )
34-
3535 setErrors ( result . error . flatten ( ) . fieldErrors )
3636
37- // Keep the optimistic state for 1 second
38- await new Promise ( ( resolve ) => setTimeout ( resolve , 1000 ) )
39-
40- return {
41- firstName : '' ,
42- lastName : '' ,
43- note : '' ,
44- inviteCode : '' ,
45- }
37+ return 'Form submission failed!'
4638 }
4739
48- const submitResult = await slowFormRequest ( result . data )
49-
50- addOptimisticState ( [ 'Form submitted successfully!' ] )
51- // Keep the optimistic state for 1 second
52- await new Promise ( ( resolve ) => setTimeout ( resolve , 1000 ) )
40+ await slowFormRequest ( result . data )
5341
54- return {
55- firstName : submitResult . firstName ,
56- lastName : submitResult . lastName ,
57- note : submitResult . note ,
58- inviteCode : submitResult . inviteCode ,
59- }
42+ return 'Form submitted successfully!'
6043 } catch ( error ) {
61- addOptimisticState ( [ `Form submission failed! ${ JSON . stringify ( error ) } ` ] )
62-
63- return {
64- firstName : '' ,
65- lastName : '' ,
66- note : '' ,
67- inviteCode : '' ,
68- }
44+ return `Form submission failed! ${ JSON . stringify ( error ) } `
6945 }
7046 }
7147
72- const [ state , formAction , isPending ] = useActionState ( handleFormSubmit , {
73- firstName : '' ,
74- lastName : '' ,
75- note : '' ,
76- inviteCode : '' ,
77- } )
48+ const [ state , formAction , isPending ] = useActionState ( handleFormSubmit , '' )
7849
7950 return (
8051 < div className = "min-w-96" >
@@ -92,6 +63,8 @@ export const ReactForm: FC = () => {
9263 < div key = { message } > { message } </ div >
9364 ) ) }
9465
66+ { state && < div > { state } </ div > }
67+
9568 < Button disabled = { isPending } > Submit</ Button >
9669 </ Form >
9770 </ div >
0 commit comments