Hi, I am trying to build a simple landing page with astro, very similar to the astro together actions presentation.
I have a form and an action, but when the actions fails (returns an error) the forms resets, witch is a bad UX.
The part of the presentation video that showing the issue: https://youtu.be/VkYQMhit_04?si=Wzj4XkGRiBOGkj8l&t=1057.
The action:
import { ActionError, defineAction, z } from "astro:actions";
export const server = {
contactUsFormSubmission: defineAction({
input: z.object({
name: z...,
email: z...,
message: z...
}),
accept: "form",
handler: (payload, ctx) => {
try {
throw new Error("Test")
console.log("Received payload:", payload);
return { payload, success: true };
} catch (e) {
throw new ActionError({
message: "Failed to submit form",
code:"INTERNAL_SERVER_ERROR"
})
}
},
}),
};
The form component:
import { experimental_withState as withState } from "@astrojs/react/actions";
import { actions } from "astro:actions";
import { useActionState, useEffect } from "react";
import { TextArea } from "../components/inputs/textArea";
import { TextInput } from "../components/inputs/textInput";
export function ContactUsForm() {
const [{ data, error }, action, pending] = useActionState(
withState(actions.contactUsFormSubmission),
{
data: {
payload: {
name: "",
email: "",
message: ""
},
success: false
},
error: undefined
}
);
return (
<form action={action}>
...
</form>
);
}
Thanks for the help 🙂
Astro Actions are an all-in-one solution for type-safe backends. Try them out in Astro 4.10: https://docs.astro.build/en/reference/configuration-reference/#experimentalactions