So we are trying to do some validation for our cart using the barebones Hydrogen quickstart in TypeScript, but we are having issues using the CartForm component.
Whenever you submit a cart form to update some attributes, Hydrogen uses the component like a form.
// in app/components/Cart.tsx
function CartLineUpdateButton({
children,
lines,
}: {
children: React.ReactNode;
lines: CartLineUpdateInput[];
}) {
return (
<CartForm
route="/cart"
action={CartForm.ACTIONS.LinesUpdate}
inputs={{lines}}
>
{children}
</CartForm>
);
}
By default, we are given an action in app/routes/($locale).cart.tsx that receives the submitted information.
// in app/routes/($locale).cart.tsx
export async function action({request, context}: ActionFunctionArgs) {
...
return json(
{
cart: cartResult,
errors,
analytics: {
cartId,
},
},
{status, headers},
);
Typically in React, the action returns information to whatever route submitted the form with “useActionData”. You can see an example in the official React documentation: https://reactrouter.com/en/main/hooks/use-action-data#useactiondata
export default function SignUp() {
const errors = useActionData();
return (
<Form method="post">
...
<p>
<button type="submit">Sign up</button>
</p>
</Form>
);
}
However, when attempting to receive information from the built-in action in app/routes/($locale).cart.tsx, the value always comes back as “undefined”. This is even after returning to the page, forcing a reload.
// in app/routes/($locale).cart.tsx
export default function Cart() {
const actionData = useActionData();
console.log("action data: " + actionData); // always undefined
How can we receive this information? Where does it go? We would like to use the “errors” value for some form validation, and display any errors. But without the action’s return value, we can never display anything in addition. We could use some help figuring this out.