Skip to content

Commit

Permalink
fix: calling onBlur on add or remove from a list (#35)
Browse files Browse the repository at this point in the history
Co-authored-by: Jcharpentier <[email protected]>
  • Loading branch information
2 people authored and stephenh committed Nov 29, 2021
1 parent ea39ea1 commit a61a728
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/formState.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,17 @@ describe("formState", () => {
expect(a1.dirty).toBeFalsy();
});

it("it calls onBlur when adding or removing to a list", () => {
const onBlur = jest.fn();
const a1 = createAuthorInputState({ books: [] }, onBlur);
expect(a1.books.dirty).toBeFalsy();
a1.books.add({ title: "t2" });
expect(a1.books.dirty).toBeTruthy();
a1.books.remove(0);
expect(a1.dirty).toBeFalsy();
expect(onBlur).toBeCalledTimes(2);
});

it("knows list of primitives are dirty", () => {
const a1 = createObjectState<AuthorInput>({ favoriteColors: { type: "value" } }, {});
expect(a1.favoriteColors.dirty).toBeFalsy();
Expand Down Expand Up @@ -1613,7 +1624,7 @@ describe("formState", () => {
// And the new book is blurred
click(r.blurNew);
// Then expect onBlur to be triggered again
expect(onBlur).toBeCalledTimes(2);
expect(onBlur).toBeCalledTimes(3);
});
});

Expand Down Expand Up @@ -1654,8 +1665,8 @@ const authorWithBooksConfig: ObjectConfig<AuthorInput> = {
},
};

function createAuthorInputState(input: AuthorInput) {
return createObjectState<AuthorInput>(authorWithBooksConfig, input);
function createAuthorInputState(input: AuthorInput, onBlur?: () => void) {
return createObjectState<AuthorInput>(authorWithBooksConfig, input, { onBlur });
}

const authorWithAddressConfig: ObjectConfig<AuthorInput> = {
Expand Down
2 changes: 2 additions & 0 deletions src/formState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,7 @@ function newListFieldState<T, K extends keyof T, U>(
this.ensureSet();
this.value.splice(typeof spliceIndex === "number" ? spliceIndex : this.value.length, 0, childState.value);
_tick.value++;
onBlur();
},

remove(indexOrValue: number | U): void {
Expand All @@ -898,6 +899,7 @@ function newListFieldState<T, K extends keyof T, U>(
}
}
_tick.value++;
onBlur();
},

reset() {
Expand Down

0 comments on commit a61a728

Please sign in to comment.