Skip to content

Commit

Permalink
fix: Allow init.input to be an array. (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenh authored Jun 23, 2021
1 parent a6c295f commit adc6195
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/formState.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,30 @@ describe("formState", () => {
expect(r.baseElement).toHaveTextContent("bob");
});

it("memoizes on init.input being an array", async () => {
// Given a component
type FormValue = Pick<AuthorInput, "firstName">;
const config: ObjectConfig<FormValue> = { firstName: { type: "value" } };
function TestComponent() {
const [, setTick] = useState(0);
const form = useFormState({
config,
init: { input: ["a", "b"], map: ([a, b]) => ({ firstName: a + b }) },
});
const onClick = () => [form.firstName.set("fred"), setTick(1)];
return (
<div>
<button data-testid="change" onClick={onClick} />
<div data-testid="firstName">{form.firstName.value}</div>
</div>
);
}
const r = await render(<TestComponent />);
expect(r.firstName()).toHaveTextContent("ab");
click(r.change);
expect(r.firstName()).toHaveTextContent("fred");
});

it("uses default if init.input is undefined", async () => {
// Given a component
function TestComponent() {
Expand Down
2 changes: 1 addition & 1 deletion src/formState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export function useFormState<T, I>(opts: UseFormStateOpts<T, I>): ObjectState<T>
}, [
config,
// If they're using init.input, useMemo on it, otherwise let the identity of init be unstable
...(init && "input" in init && "map" in init ? [init.input] : []),
...(init && "input" in init && "map" in init ? (Array.isArray(init.input) ? init.input : [init.input]) : []),
]);

// Use useEffect so that we don't touch the form.init proxy during a render
Expand Down

0 comments on commit adc6195

Please sign in to comment.