vantezzen / auto-form

🌟 A React component that automatically creates a @shadcn/ui form based on a zod schema.
https://vantezzen.github.io/auto-form/
2.29k stars 81 forks source link

reset form #16

Closed sevta closed 11 months ago

sevta commented 11 months ago

is there a way to reset form value ? or get form instance ?

vantezzen commented 11 months ago

You can use a controlled form to get access to the state variables and reset the values. See https://github.com/vantezzen/auto-form#controlled-form

enesbala5 commented 1 month ago

This is not sufficient in my opinion - there should be an option to have children within the form itself, or pass a ref. A context object with functions would be good too. Library is great otherwise but you shouldn't have to give up validation and complicate everything for such a simple functionality.

enesbala5 commented 1 month ago

Or the non-React way could be to add a name property and instruct people to reset through the DOM - any solution is better than having to implement the controlled form.

Edit: I am guessing this wouldn't be possible because of the local state on the component. Possibly a key prop could achieve the same thing, just resetting the component fully.

enesbala5 commented 1 month ago

Solution with key prop. Working great for my use case,

Parent Component:

"use client";

...
interface InnerFormProps {
    className?: string;
}

export const InnerForm = (props: InnerFormProps) => {
    const { className } = props;

    const [refreshKey, setRefreshForm] = useState<number>(0);

    const refresh = () => {
        setRefreshForm((val) => val + 1);
    };

    const resetButton = useRef<HTMLButtonElement>(null);

        return (
        <section key={refreshKey} className={cn("w-full", className)}>
            <AutoForm 
                onSubmit={async (values: InnerFormType) => {
                ...

                // Reset fields
                resetButton?.current?.click();
            }}
        >
            <div className="flex flex-wrap items-center justify-between gap-4">
                <button type="submit">
                    Send
                </button>
                {/* Reset button with ref using DefaultButton and ghost class with lucide icon */}
                <button
                    type="reset"
                    onClick={refresh}
                    ref={resetButton}
                >
                    Reset
                </DefaultButton>
            </div>

        <Autoform>
    </section>
)