Usage of createFormHookContexts and getting basic type of form
While I've seen a couple of threads touching some similar questions, I wanted to ask this once more explicitly:
1. Am I right that I run createFormHookContexts ONCE per application and have all forms in my app -although totally unrelated- using the same useAppForm hook based on the createFormHook using the above defined context? Do I need to wrap my application in the "formContext" (like used to with other createContext's using formContext.Provider)?
2. What is the recommended/easiest way to keep my old behavior on passing the formApi to hooks that MUST NOT BE Functional Components, i.e., hooks. While withForm() allows to wrap my FC's and force them to take a form, i have plenty of hooks (useXXXX) that also need to access the form + need to know the overall DataType. My current approach (using the 1.X version) is doing as following:
export type FormType<FormData> = ComponentProps<
ReturnType<typeof withForm<FormData, any, any, any, any, any, any, any, any, any>>
>["form"];
export type FormTypeV2<FormData> = ReactFormExtendedApi<FormData, any, any, any, any, any, any, any, any, any>;
I understand that this destroys/works against the wanted behavior and potential of Tanstack form and generic typing, but - in our case (and from what I read many others) - 90% of our forms are so stupid simple that most of hooks/FCs just need to know the datastructure and not every generic detail.
@crutchcorn Am I missing something out or is the only possible way to get to this simplificated formType (for hooks, not FC's) by inferring the type from one of the helper functions or using one of the FormApi<> types? Would it make sense to establish an "useWithForm" hook wrapper (to wrap hooks that require the form) similar to withForm for FCs, that enforces to get a form based on its options, i.e., the defaultValues?
1 Reply
noble-gold•6mo ago
for 1.
Yes, you create it once. To make a form per file, you‘ll use
useAppForm
which will then allow you to access the context providers yourForm.AppForm
and .AppField
do you have an example of your usecase in point 2?