Skip to content

Commit

Permalink
Try useOptimistic
Browse files Browse the repository at this point in the history
This breaks progressive enhancement, and the `prevState` in the reducer
is always `undefined`. Therefore, only the quantity gets rendered
optimistically, not the total quantity.
  • Loading branch information
unstubbable committed Jan 12, 2024
1 parent 66a4c1e commit a493ac1
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion apps/shared-app/src/client/product.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,23 @@ export interface ProductProps {
}

export function Product({buy}: ProductProps): JSX.Element {
const [result, formAction] = ReactDOM.useFormState(buy, undefined);
const [formState, formAction] = ReactDOM.useFormState(
async (prevResult: BuyResult | undefined, formData: FormData) => {
setOptimisticResult(parseInt(formData.get(`quantity`) as string, 10));

return buy(prevResult, formData);
},
undefined,
);

const [result, setOptimisticResult] = React.useOptimistic<
BuyResult | undefined,
number
>(formState, (prevResult, quantity) => ({
status: `success`,
quantity,
totalQuantityInSession: prevResult?.totalQuantityInSession ?? 0 + quantity,
}));

return (
<form action={formAction}>
Expand Down

0 comments on commit a493ac1

Please sign in to comment.