Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

contexts.lib.ts

28 lines865 Bytes

1import { createContext, useContext } from 'react'
2import type { AnyInternalFieldApi } from '@tanstack/form-core/internals'
3import type { InternalReactFormApi } from '../ReactForm/ReactFormApi.lib'
4​
5export const FormContext = createContext<InternalReactFormApi | null>(null)
6export const FieldContext = createContext<AnyInternalFieldApi | null>(null)
7​
8export function useFieldContext(): AnyInternalFieldApi {
9 const field = useContext(FieldContext)
10 if (field === null) {
11 throw new Error(
12 'TanStack Form: Field components must be used within a `form.Field` component.',
13 )
14 }
15​
16 return field
18​
19export function useFormContext(): InternalReactFormApi {
20 const form = useContext(FormContext)
21 if (form === null) {
22 throw new Error(
23 'TanStack Form: Form components must be used within a `form.AppForm` component.',
24 )
25 }
26​
27 return form