Skip to content

Commit c1e392f

Browse files
committed
fix: simplify optimistic state
1 parent 99da8dd commit c1e392f

2 files changed

Lines changed: 8 additions & 12 deletions

File tree

src/components/HookForm/HookForm.tsx

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { slowFormRequest } from '@/utils/slow-form-request'
1717

1818
export const HookForm: FC = () => {
1919
const [isPending, startTransition] = useTransition()
20-
const [optimisticState, addOptimisticState] = useOptimistic<string[]>([])
20+
const [optimisticState, addOptimisticState] = useOptimistic<string>('')
2121
const {
2222
register,
2323
handleSubmit,
@@ -36,17 +36,17 @@ export const HookForm: FC = () => {
3636
const handleFormSubmit = (data: FormSchema) => {
3737
startTransition(async () => {
3838
try {
39-
addOptimisticState(['Submitting form...'])
39+
addOptimisticState('Submitting form...')
4040

4141
await slowFormRequest(data)
4242

43-
addOptimisticState(['Form submitted successfully!'])
43+
addOptimisticState('Form submitted successfully!')
4444
// Keep the optimistic state for 1 second
4545
await new Promise((resolve) => setTimeout(resolve, 1000))
4646

4747
reset()
4848
} catch (error) {
49-
addOptimisticState([`Form submission failed! ${JSON.stringify(error)}`])
49+
addOptimisticState(`Form submission failed! ${JSON.stringify(error)}`)
5050
}
5151
})
5252
}
@@ -63,9 +63,7 @@ export const HookForm: FC = () => {
6363
</FieldWrapper>
6464
))}
6565

66-
{optimisticState.map((state, index) => (
67-
<p key={index}>{state}</p>
68-
))}
66+
{optimisticState && <div>{optimisticState}</div>}
6967

7068
<Button disabled={isPending}>Submit</Button>
7169
</Form>

src/components/ReactForm/ReactForm.tsx

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ type ErrorsState = Partial<{
2020
export const ReactForm: FC = () => {
2121
const [errors, setErrors] = useState<ErrorsState | null>(null)
2222

23-
const [optimisticState, addOptimisticState] = useOptimistic<string[]>([])
23+
const [optimisticState, addOptimisticState] = useOptimistic<string>('')
2424

2525
const handleFormSubmit = async (previousState: string, formData: FormData) => {
2626
try {
2727
setErrors(null)
2828

29-
addOptimisticState(['Submitting form...'])
29+
addOptimisticState('Submitting form...')
3030

3131
const formDataEntries = Object.fromEntries(formData.entries())
3232
const result = formSchema.safeParse(formDataEntries)
@@ -70,9 +70,7 @@ export const ReactForm: FC = () => {
7070
</FieldWrapper>
7171
))}
7272

73-
{optimisticState.map((message) => (
74-
<div key={message}>{message}</div>
75-
))}
73+
{optimisticState && <div>{optimisticState}</div>}
7674

7775
{state && <div>{state}</div>}
7876

0 commit comments

Comments
 (0)