How do I integrate tanstack query with formOptions? #1311
Replies: 1 comment 2 replies
-
Check the TsQuery example You could do import { z } from "zod";
import { formOptions } from "@tanstack/react-form";
export const DataSchema = z.object({
name: z.string(),
});
type Data = z.infer<typeof DataSchema>;
export const getMyFormOpts = (defaultValues?: Data) =>
formOptions({
defaultValues: {
name: defaultValues?.name || "",
},
});
const MyComponent = () => {
const { data } = useQuery();
const formOpts = useMemo(
() => ({
...getMyFormOpts(data),
validators: {
onChange: DataSchema,
},
onSubmit: async ({ value }) => {
// Do something with form data
},
}),
[data]
);
const form = useAppForm(formOpts);
form.setFormValue("name", data.name); // Currently setting value after fetching...
return (
<form
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit();
}}
>
<form.Field name="name">
{({ state, handleChange, handleBlur }) => {
return (
<Input
defaultValue={state.value}
onChange={(e) => handleChange(e.target.value)}
onBlur={handleBlur}
placeholder="Enter Name"
/>
);
}}
</form.Field>
</form>
);
}; |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am trying to find a way to use formOptions with tanstack query when formOptions is in a file of its own and tanstack query is in a component file
I can see if I create some wrapper functions/hooks then it might work but I am not sure if that is the correct way or if there are something that is already implemented in tanstack form that can be used out of the box
The reason I have formOptions in a different file is that it is reused in other forms (I didnt write it in the example)
schema.ts
component.tsx
Beta Was this translation helpful? Give feedback.
All reactions