Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/react-form/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from '@tanstack/form-core'

export { useStore } from '@tanstack/react-store'
export { useStore } from './useStore'

export * from './createFormHook'
export * from './types'
Expand Down
44 changes: 44 additions & 0 deletions packages/react-form/src/useStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useStore as _useStore } from '@tanstack/react-store'
import type { AnyAtom } from '@tanstack/react-store'

type AtomSnapshot<TAtom> = TAtom extends { get: () => infer TSnapshot }
? TSnapshot
: undefined

/**
* Subscribe to a store atom and return its current state.
*
* When called without a `selector` the full atom snapshot is returned.
*
* @example
* // Return the full form state (selector optional for back-compat)
* const formState = useStore(form.store)
*
* @example
* // Return a specific slice
* const isValid = useStore(form.store, (s) => s.isValid)
*/
export function useStore<TAtom extends AnyAtom | undefined>(
atom: TAtom,
): AtomSnapshot<TAtom>

export function useStore<TAtom extends AnyAtom | undefined, T>(
atom: TAtom,
selector: (snapshot: AtomSnapshot<TAtom>) => T,
compare?: (a: T, b: T) => boolean,
): T

export function useStore<TAtom extends AnyAtom | undefined, T>(
atom: TAtom,
selector?: (snapshot: AtomSnapshot<TAtom>) => T,
compare?: (a: T, b: T) => boolean,
): T | AtomSnapshot<TAtom> {
// When no selector is provided fall back to the identity function so that
// callers that were using `useStore(form.store)` without a selector
// (as was valid in prior releases) continue to work.
return _useStore(
atom,
(selector ?? ((s: any) => s)) as (snapshot: AtomSnapshot<TAtom>) => T,
compare,
)
}
Loading