useFormContext hook #1003
-
|
I think it would be convenient to have a useFormContext hook similar to react-hook form (https://react-hook-form.com/docs/useformcontext) for multi-step/nested forms |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
|
@crutchcorn I feel like you've heard this request several times. what is the reasoning that there is no "simple" <FormProvider/>, useFormContext() pattern? |
Beta Was this translation helpful? Give feedback.
-
|
Multi-step and nested forms are not a good fit for context. Instead, we just shipped: https://tanstack.com/form/latest/docs/framework/react/guides/form-groups |
Beta Was this translation helpful? Give feedback.
-
|
@crutchcorn thanks for your answers. I'm not even talking about multi-step forms. I'll try to explain my painpoint "briefly" I have one wrapper component creating the form: export const createPostDefaultValues = {
access: PublicPostDtoPostType.FREE as PublicPostDtoPostType,
price: 2,
text: "",
aspectRatio: CarouselAspectRatio.SQUARE,
postTarget: "profile",
};const form = useAppForm({
defaultValues: createPostDefaultValues,
validators: {
onSubmit: postPostFormSchema,
},
});
return (
<Drawer title={t("createPost.title")} loading={isPending}>
<CreatePostContent form={form} />
</Drawer>
);The child gets the form via props: export const CreatePostContent = withForm({
defaultValues: createPostDefaultValues, // <-- do I need defaultValues here again?
render({ form }) {
// const { t } = useTranslation(); <-- breaks (react-hooks/rules-of-hooks)
return <CreatePostContentInner form={form} />;
},
});Now my first question is: What is the correct type of The approach I currently have feels very brittle: type PostFormInstance = Parameters<typeof CreatePostContent>[0]["form"];
function CreatePostContentInner({
form,
}: {
form: PostFormInstance;
}) {Second question: What if I have components inside the form that are deeply nested? How are those components supposed to access the form instance? Do I really have to prop-drill the form all the way down? For example: // DeepNestedComponent.tsx
function DeepChild() {
// How do I retrieve the "postTarget" value from the form here?
return <p>{theRetrievedValue}</p>;
} |
Beta Was this translation helpful? Give feedback.
Multi-step and nested forms are not a good fit for context. Instead, we just shipped:
https://tanstack.com/form/latest/docs/framework/react/guides/form-groups