TanStackT
TanStack2mo ago
14 replies
full-green

How to "globally" merge 422 server errors

My objective here is to create a wrapper around the useAppForm hook that would automatically handle 422 errors and correctly assign these to the field.state.meta.errors object. However I had some troubles with the generics.

This code is not exactly right, but it's close to what I am trying to do
const { useAppForm } = createFormHook({
    fieldComponents: {},
    formComponents: {},
    fieldContext,
    formContext,
});

// I did this to help me avoid to write all the generics necessary to wrap the hook
function wrap<TArgs extends Array<unknown>, TReturn, TWrappedReturn>(
    fn: (...args: TArgs) => TReturn,
    wrapper: (
        fn: (...args: TArgs) => TReturn,
    ) => (...args: TArgs) => TWrappedReturn,
) {
    return wrapper(fn);
}

export const useSuperForm = wrap(useAppForm, (useForm) => (props) => {
    const form = useForm({
        ...props,
        validators: {
            ...props.validators,
            async onSubmitAsync() {
                try {
                    return await props.validators?.onSubmitAsync?.(...args);
                } catch (error) {
                    if (error instanceof ZodError) {
                        // automatically handle schema errors as well
                        return {...errors, ...}
                    }
                    if (isAxiosError(error)) {
                        // merge with form errors
                        return {...errors, ...}
                    }
                }
            },
        },
    });
    return form
});


I also tried something similar but instead of using the validators, I tried wrapping the handleSubmit function. The issue with this one is that the field.state.meta.errors type is undefined[] or something similar.

So my question here is: is there a better way to accomplish this, or is it even possible at all?

* If there are any docs around this topic I'll be happy to read through.
* I am not a native speaker, so please dismiss any english mistakes.
Was this page helpful?