#prevent form reset on error

1 messages · Page 1 of 1 (latest)

fresh spoke
#

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 🙂

deep sphinx
#

Does e.preventDefault() not do it?

fresh spoke
#

on what? on Submit? but then I loose all the uaeActionState... I tied on onReset either, and check there is there is an error..

deep sphinx
#

Yes it would be on onSubmit

I'm not familiar with the react library you are using so not sure how to make it work with that setup