Skip to content
Source
Sign inSign up
TanStack/form

[v2] Allow `createFormHook` to define default form options #2298

ClosedLeCarbonator(GitHub profile, opens in a new tab) opened this issue 2 comments

Applications often want forms created by the same hook to share a small set of behaviors. createFormHook could support this by accepting non-generic default options, creating a reusable preset that is automatically applied whenever the resulting useAppForm hook is used.

For example:

export const { useAppForm } = createFormHook({
  // ...
  defaultOptions: {
    // NOT: defaultValues, validators, onSubmit
    // YES: listeners, onSubmitInvalid, errorVisibility (generalized to `any`?)
    errorVisibility: ({ fieldState }) => fieldState.meta.isTouched,
  },
})

useAppForm({}) // Contains the default errorVisibility

This would let users configure shared behavior once while continuing to provide form-specific values, validators, and submission logic to each call to useAppForm.

Important

The defaults should be limited to options that do not depend on the form's generic types. Options such as defaultValues, validators, and onSubmit would therefore remain form-specific. Possible defaults include listeners, onSubmitInvalid, and errorVisibility, although supporting errorVisibility may require generalizing its types to any.

  1. LeCarbonator(GitHub profile, opens in a new tab) added labelstype: enhancement

  2. LeCarbonator(GitHub profile, opens in a new tab) added labelsscope: react

  3. LeCarbonator(GitHub profile, opens in a new tab) added labelsarea: runtime

  4. LeCarbonator(GitHub profile, opens in a new tab) added labelsarea: types

  5. lucas-dtrn(GitHub profile, opens in a new tab)commented

    I already had to create a workaround to define default options.

    const showErrorsAfterBlurOrSubmit = createErrorVisibility(
      ({ fieldState, state }) => fieldState.meta.isBlurred || state.submissionAttempts > 0,
    );
    
    const { useAppForm: baseAppForm } = createFormHook({
      fieldComponents,
      formComponents,
    });
    
    export const useAppForm: typeof useBaseAppForm = (options) =>
      useBaseAppForm({
        ...options,
        errorVisibility: options.errorVisibility ?? showErrorsAfterBlurOrSubmit,
      });

    But I would definitely prefer a native solution.

  6. Should be available in v2.0.0@alpha.1 @lucas-dtrn

Sign in to join this conversation.