Skip to content

Commit

Permalink
fix: useOnCollectionChange and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
HugoPerard committed Sep 30, 2024
1 parent 377b827 commit a2d955d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
21 changes: 21 additions & 0 deletions apps/examples/cypress/e2e/collection.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,25 @@ describe("Collection", () => {

cy.get('[data-test="conditioned[0]"').should("not.exist");
});

it("Managed from form collection", () => {
cy.field("items[0]").should("not.exist");

cy.get("button").contains("Prepend").click();
cy.get("button").contains("Append").click();

cy.field("items[0]").should("exist");
cy.field("items[1]").should("exist");

cy.get("button").contains("Remove first item").click();

cy.field("items[1]").should("not.exist");

cy.get("button").contains("Set 3 items").click();

cy.field("items[0]").should("exist");
cy.field("items[1]").should("exist");
cy.field("items[2]").should("exist");
cy.field("items[3]").should("not.exist");
});
});
20 changes: 9 additions & 11 deletions packages/formiz-core/src/useForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,17 @@ export const useForm = <Values extends object = any>(
export const useOnCollectionsChange = (
useStore?: UseBoundStore<StoreApi<Store>>
) => {
const timeoutRef = useRef<NodeJS.Timeout>();
const prevCollectionsCountRef = useRef(-1);

useStore?.((state) => {
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
const collectionsCount = state.collections.size;
if (
prevCollectionsCountRef.current !== -1 &&
collectionsCount === prevCollectionsCountRef.current
)
return;
prevCollectionsCountRef.current = collectionsCount;
});
const collectionsCount = state.collections.size;
if (
prevCollectionsCountRef.current !== -1 &&
collectionsCount === prevCollectionsCountRef.current
) {
return prevCollectionsCountRef.current;
}
prevCollectionsCountRef.current = collectionsCount;
return prevCollectionsCountRef.current;
});
};
Expand Down

0 comments on commit a2d955d

Please sign in to comment.