TanStackT
TanStack3mo ago
15 replies
urgent-maroon

How do you pass the form via the context api?

To preface: This is probably not a great idea but I'm trying to experiment with context and the idea of compound components.

I'm trying to pass the form produced by useForm() to a context provider with the goal of using the hook in child components, here's what I have so far:

import { useForm } from '@tanstack/react-form'
import { createContext, useContext, type ReactNode } from 'react'
import z from 'zod'

export function createForm<Z extends z.ZodType>(
  formSchema: Z,
  defaultValues: z.input<Z>,
  submitHandler: (value: z.input<Z>) => void,
) {
  return useForm({
    defaultValues: defaultValues,
    validators: {
      onSubmit: formSchema,
    },
    onSubmit: ({ value }) => {
      submitHandler(value)
    },
  })
}

type FormInstance = ReturnType<typeof createForm>

const FormContext = createContext<FormInstance | null>(null)

const addExpenseFormSchema = z.object({
  description: z
    .string()
    .min(1, 'You must provide a description')
    .max(30, "Description can't exceed 30 characters"),
  amount: z.number().min(1, 'You must provide the amount'),
  category: z.string().refine((val) => val !== '', {
    message: 'You must specify a category',
  }),
})

export const FormProvider = ({ children }: { children: ReactNode }) => {
  const form = createForm(
    addExpenseFormSchema,
    {amount: 0, category: "", description: ""},
    console.log,
  )
  return <FormContext.Provider value={form}>{children}</FormContext.Provider>
}

export const useExpenseFormContext = () => {
  const context = useContext(FormContext)
  if (!context) {
    throw new Error('useMyFormContext must be used within FormProvider')
  }
  return context
}


When passing the form into the provider as the value I get the following type error: https://pastebin.com/id9MekYP

I'm guessing this is due to the use of generics, I suppose it's more to say this is a Zod/Typescript issue but I'm wondering if someone else has attempted something similar.
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Was this page helpful?