Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions apps/shared-app/src/client/product.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,29 @@ export interface ProductProps {
}

export function Product({buy}: ProductProps): JSX.Element {
const [result, formAction] = ReactDOM.useFormState(buy, undefined);
const [formState, formAction] = ReactDOM.useFormState(buy, undefined);

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

return (
<form action={formAction}>
<form
action={formAction}
onSubmit={(event) => {
const formData = new FormData(event.currentTarget);

React.startTransition(() => {
setOptimisticResult(parseInt(formData.get(`quantity`) as string, 10));
});
}}
>
<p className="my-2">
This is a client component that renders a form with a form action. On
submit, a server action is called with the current form data, which in
Expand Down