diff --git a/.changeset/tidy-filters-prev-value.md b/.changeset/tidy-filters-prev-value.md new file mode 100644 index 00000000..b38a1385 --- /dev/null +++ b/.changeset/tidy-filters-prev-value.md @@ -0,0 +1,5 @@ +--- +'@lambdacurry/forms': patch +--- + +Fix `useOnFormValueChange` passing the new value as `prevValue`. The hook now keeps one subscription across renders, so `prevValue` stays correct when a change is reported after a re-render (e.g. `useFieldArray`), and it no longer calls `onChange` when a notification leaves the value unchanged. Also speed up data-table filter array helpers (`uniq`, `intersection`, `removeUniq`, `getColumnValues`). diff --git a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx index 492d233f..8b5d37b8 100644 --- a/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx +++ b/apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx @@ -4,6 +4,7 @@ import { useOnFormValueChange } from '@lambdacurry/forms/remix-hook-form/hooks/u import { Select } from '@lambdacurry/forms/remix-hook-form/select'; import { TextField } from '@lambdacurry/forms/remix-hook-form/text-field'; import type { Meta, StoryContext, StoryObj } from '@storybook/react-vite'; +import { useFieldArray } from 'react-hook-form'; import { expect, userEvent, within, waitFor } from '@storybook/test'; import { useState, useMemo, useCallback } from 'react'; import { useFetcher } from 'react-router'; @@ -576,3 +577,159 @@ export const ConditionalFields: Story = { ], }; */ + +// ============================================================================ +// Story 4: Previous Value +// ============================================================================ +const previousValueSchema = z.object({ + nickname: z.string(), +}); + +type PreviousValueFormData = z.infer; + +const PreviousValueExample = () => { + const fetcher = useFetcher(); + const [changes, setChanges] = useState([]); + + const rawMethods = useRemixForm({ + resolver: zodResolver(previousValueSchema), + defaultValues: { nickname: 'Al' }, + fetcher, + submitConfig: { action: '/', method: 'post' }, + }); + + const methods = useMemo(() => rawMethods, [rawMethods]); + + // Log every (prev → next) pair, and capitalize the first letter. The setValue call re-enters the + // hook for the same field, so the log also shows that nested changes get the right previous value. + const handleNicknameChange = useCallback( + (next: string, prev: string) => { + setChanges((log) => [...log, `${JSON.stringify(prev)} → ${JSON.stringify(next)}`]); + + const capitalized = next.charAt(0).toUpperCase() + next.slice(1); + if (capitalized !== next) methods.setValue('nickname', capitalized); + }, + [methods], + ); + + useOnFormValueChange({ + name: 'nickname', + methods, + onChange: handleNicknameChange, + }); + + return ( + + + + {changes.length === 0 ? ( +

No changes yet

+ ) : ( +
    + {changes.map((change, index) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: append-only log, entries can repeat +
  1. {change}
  2. + ))} +
+ )} +
+
+ ); +}; + +const getChangeLog = (canvas: ReturnType) => + canvas.getAllByRole('listitem').map((item: HTMLElement) => item.textContent); + +export const PreviousValue: Story = { + play: async ({ canvasElement }: StoryContext) => { + const canvas = within(canvasElement); + + const input = await canvas.findByLabelText(/nickname/i); + expect(canvas.getByText('No changes yet')).toBeInTheDocument(); + + // Plain edits: each change receives the value before it + await userEvent.type(input, 'ex'); + await waitFor(() => expect(getChangeLog(canvas)).toEqual(['"Al" → "Ale"', '"Ale" → "Alex"'])); + + // Same-field normalization: typing "a" is rewritten to "A" by setValue inside onChange. + // The nested change must see "a" as its previous value, and the next edit must see "A". + await userEvent.clear(input); + await userEvent.type(input, 'al'); + + await waitFor(() => expect(input).toHaveValue('Al')); + expect(getChangeLog(canvas).slice(2)).toEqual(['"Alex" → ""', '"" → "a"', '"a" → "A"', '"A" → "Al"']); + }, + decorators: [ + withReactRouterStubDecorator({ + routes: [{ path: '/', Component: PreviousValueExample }], + }), + ], +}; + +// ============================================================================ +// Story 5: Field Array +// ============================================================================ +type GuestListFormData = { guests: { name: string }[] }; + +const FieldArrayExample = () => { + const fetcher = useFetcher(); + const [changes, setChanges] = useState([]); + + const methods = useRemixForm({ + defaultValues: { guests: [] }, + fetcher, + submitConfig: { action: '/', method: 'post' }, + }); + + const { fields, append } = useFieldArray({ control: methods.control, name: 'guests' }); + + // useFieldArray re-renders before it reports the change, so this also checks that the hook's + // tracked previous value survives a render (useRemixForm returns a new methods object each time). + const handleGuestsChange = useCallback( + (next: GuestListFormData['guests'], prev: GuestListFormData['guests']) => + setChanges((log) => [...log, `${prev.length} → ${next.length} guests`]), + [], + ); + + useOnFormValueChange({ + name: 'guests', + methods, + onChange: handleGuestsChange, + }); + + return ( + + + +

{fields.length} guests

+

{changes.length ? changes.join(', ') : 'No changes yet'}

+
+
+ ); +}; + +export const FieldArray: Story = { + play: async ({ canvasElement }: StoryContext) => { + const canvas = within(canvasElement); + + const addButton = await canvas.findByRole('button', { name: /add guest/i }); + expect(canvas.getByTestId('guest-changes')).toHaveTextContent('No changes yet'); + + await userEvent.click(addButton); + await userEvent.click(addButton); + + await canvas.findByText('2 guests'); + await waitFor(() => expect(canvas.getByTestId('guest-changes')).toHaveTextContent(/^0 → 1 guests, 1 → 2 guests$/)); + }, + decorators: [ + withReactRouterStubDecorator({ + routes: [{ path: '/', Component: FieldArrayExample }], + }), + ], +}; diff --git a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts index e6334d28..63af2a30 100644 --- a/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts +++ b/packages/components/src/remix-hook-form/hooks/use-on-form-value-change.ts @@ -1,4 +1,4 @@ -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useFormContext, type FieldPath, @@ -26,7 +26,8 @@ export interface UseOnFormValueChangeOptions< */ name: TName; /** - * Callback function that runs when the field value changes + * Callback function that runs when the field value changes. + * Not called when a notification leaves the value unchanged (compared with `Object.is`). * @param value - The new value of the watched field * @param prevValue - The previous value of the watched field */ @@ -84,26 +85,43 @@ export const useOnFormValueChange = < const contextMethods = useFormContext(); const formMethods = (providedMethods || contextMethods) as WatchableFormMethods | null; + // `methods` from useRemixForm is a new object on every render, but watch and getValues are stable. + // Subscribing on those (and reading onChange through a ref) keeps one subscription alive across + // renders, so the tracked previous value survives a render that happens before RHF notifies + // (e.g. useFieldArray's append). + const watch = formMethods?.watch; + const getValues = formMethods?.getValues; + const onChangeRef = useRef(onChange); + + useEffect(() => { + onChangeRef.current = onChange; + }, [onChange]); + useEffect(() => { // Early return if no form methods are available or hook is disabled - if (!enabled || !formMethods || !formMethods.watch || !formMethods.getValues) return; + if (!enabled || !watch || !getValues) return; - const { watch, getValues } = formMethods; + // Track the previous value ourselves: inside a watch callback the form state already holds the + // new value, so getValues(name) cannot provide it. Seeding here also resets it when `name` changes. + let prevValue = getValues(name); // Subscribe to the field value changes - const subscription = watch(((value, { name: changedFieldName }) => { - // Only trigger onChange if the watched field changed - if (changedFieldName === name) { - const currentValue = value[name] as PathValue; - // Get previous value from the form state - const prevValue = getValues(name); + const subscription = watch(((_value, { name: changedFieldName }) => { + const currentValue = getValues(name); + const previousValue = prevValue; - onChange(currentValue, prevValue); + // Update tracking on every notification (reset() fires without a field name), and before + // onChange: a setValue on this field inside onChange re-enters this callback synchronously. + prevValue = currentValue; + + // Only trigger onChange if the watched field changed. RHF notifies twice for a setValue on a + // controlled field, so skip notifications that leave the value as it was. + if (changedFieldName === name && !Object.is(currentValue, previousValue)) { + onChangeRef.current(currentValue, previousValue); } }) as WatchObserver); // Cleanup subscription on unmount - return () => subscription.unsubscribe(); - }, [name, onChange, enabled, formMethods]); + }, [name, enabled, watch, getValues]); }; diff --git a/packages/components/src/ui/data-table-filter/core/filters.ts b/packages/components/src/ui/data-table-filter/core/filters.ts index 59b5532a..b4a549e2 100644 --- a/packages/components/src/ui/data-table-filter/core/filters.ts +++ b/packages/components/src/ui/data-table-filter/core/filters.ts @@ -228,9 +228,8 @@ export function getColumnValues( } if (column.options) { - return raw - .map((v) => column.options?.find((o) => o.value === v)?.value) - .filter((v) => v !== undefined && v !== null); + const optionsMap = new Map(column.options.map((o) => [o.value, o.value])); + return raw.map((v) => optionsMap.get(v as string)).filter((v) => v !== undefined && v !== null); } if (column.transformOptionFn) { diff --git a/packages/components/src/ui/data-table-filter/lib/array.ts b/packages/components/src/ui/data-table-filter/lib/array.ts index af9b218d..ac35b732 100644 --- a/packages/components/src/ui/data-table-filter/lib/array.ts +++ b/packages/components/src/ui/data-table-filter/lib/array.ts @@ -1,5 +1,6 @@ export function intersection(a: T[], b: T[]): T[] { - return a.filter((x) => b.includes(x)); + const set = new Set(b); + return a.filter((x) => set.has(x)); } /** @@ -97,9 +98,19 @@ function deepEqual(a: unknown, b: unknown): boolean { export function uniq(arr: T[]): T[] { // Use a Map where key is the deep hash and value is an array of items sharing the same hash. const seen = new Map(); + const primitives = new Set(); const result: T[] = []; for (const item of arr) { + const type = typeof item; + if (item === null || (type !== 'object' && type !== 'function')) { + if (!primitives.has(item)) { + primitives.add(item); + result.push(item); + } + continue; + } + const hash = deepHash(item); if (seen.has(hash)) { // There is a potential duplicate; check the stored items with the same hash. @@ -138,7 +149,8 @@ export function addUniq(arr: T[], values: T[]): T[] { } export function removeUniq(arr: T[], values: T[]): T[] { - return arr.filter((v) => !values.includes(v)); + const set = new Set(values); + return arr.filter((v) => !set.has(v)); } export function isAnyOf(value: T, values: T[]): boolean {