Skip to content

Commit a493ac1

Browse files
committed
Try useOptimistic
This breaks progressive enhancement, and the `prevState` in the reducer is always `undefined`. Therefore, only the quantity gets rendered optimistically, not the total quantity.
1 parent 66a4c1e commit a493ac1

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

apps/shared-app/src/client/product.tsx

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,23 @@ export interface ProductProps {
1515
}
1616

1717
export function Product({buy}: ProductProps): JSX.Element {
18-
const [result, formAction] = ReactDOM.useFormState(buy, undefined);
18+
const [formState, formAction] = ReactDOM.useFormState(
19+
async (prevResult: BuyResult | undefined, formData: FormData) => {
20+
setOptimisticResult(parseInt(formData.get(`quantity`) as string, 10));
21+
22+
return buy(prevResult, formData);
23+
},
24+
undefined,
25+
);
26+
27+
const [result, setOptimisticResult] = React.useOptimistic<
28+
BuyResult | undefined,
29+
number
30+
>(formState, (prevResult, quantity) => ({
31+
status: `success`,
32+
quantity,
33+
totalQuantityInSession: prevResult?.totalQuantityInSession ?? 0 + quantity,
34+
}));
1935

2036
return (
2137
<form action={formAction}>

0 commit comments

Comments
 (0)