Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/tidy-filters-prev-value.md
Original file line number Diff line number Diff line change
@@ -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`).
157 changes: 157 additions & 0 deletions apps/docs/src/remix-hook-form/use-on-form-value-change.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -576,3 +577,159 @@ export const ConditionalFields: Story = {
],
};
*/

// ============================================================================
// Story 4: Previous Value
// ============================================================================
const previousValueSchema = z.object({
nickname: z.string(),
});

type PreviousValueFormData = z.infer<typeof previousValueSchema>;

const PreviousValueExample = () => {
const fetcher = useFetcher();
const [changes, setChanges] = useState<string[]>([]);

const rawMethods = useRemixForm<PreviousValueFormData>({
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 (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="w-96 space-y-4">
<TextField
name="nickname"
label="Nickname"
description="Capitalized automatically. Each change is logged with its previous value."
/>
{changes.length === 0 ? (
<p>No changes yet</p>
) : (
<ol aria-label="Change log" className="list-decimal pl-6 text-sm">
{changes.map((change, index) => (
// biome-ignore lint/suspicious/noArrayIndexKey: append-only log, entries can repeat
<li key={index}>{change}</li>
))}
</ol>
)}
</fetcher.Form>
</RemixFormProvider>
);
};

const getChangeLog = (canvas: ReturnType<typeof within>) =>
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<string[]>([]);

const methods = useRemixForm<GuestListFormData>({
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 (
<RemixFormProvider {...methods}>
<fetcher.Form onSubmit={methods.handleSubmit} className="w-96 space-y-4">
<Button type="button" onClick={() => append({ name: `Guest ${fields.length + 1}` })}>
Add guest
</Button>
<p>{fields.length} guests</p>
<p data-testid="guest-changes">{changes.length ? changes.join(', ') : 'No changes yet'}</p>
</fetcher.Form>
</RemixFormProvider>
);
};

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 }],
}),
],
};
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from 'react';
import { useEffect, useRef } from 'react';
import {
useFormContext,
type FieldPath,
Expand Down Expand Up @@ -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
*/
Expand Down Expand Up @@ -84,26 +85,43 @@ export const useOnFormValueChange = <
const contextMethods = useFormContext<TFieldValues>();
const formMethods = (providedMethods || contextMethods) as WatchableFormMethods<TFieldValues> | 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<TFieldValues, TName>;
// 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<TFieldValues>);

// Cleanup subscription on unmount

return () => subscription.unsubscribe();
}, [name, onChange, enabled, formMethods]);
}, [name, enabled, watch, getValues]);
};
5 changes: 2 additions & 3 deletions packages/components/src/ui/data-table-filter/core/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,8 @@ export function getColumnValues<TData, TType extends ColumnDataType, TVal>(
}

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) {
Expand Down
16 changes: 14 additions & 2 deletions packages/components/src/ui/data-table-filter/lib/array.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export function intersection<T>(a: T[], b: T[]): T[] {
return a.filter((x) => b.includes(x));
const set = new Set(b);
return a.filter((x) => set.has(x));
}

/**
Expand Down Expand Up @@ -97,9 +98,19 @@ function deepEqual(a: unknown, b: unknown): boolean {
export function uniq<T>(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<string, T[]>();
const primitives = new Set<unknown>();
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.
Expand Down Expand Up @@ -138,7 +149,8 @@ export function addUniq<T>(arr: T[], values: T[]): T[] {
}

export function removeUniq<T>(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<T>(value: T, values: T[]): boolean {
Expand Down
Loading