From a2d955d2f86ed423d6483b487a6c99d26a959327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20Pe=CC=81rard?= Date: Mon, 30 Sep 2024 17:51:04 +0200 Subject: [PATCH] fix: useOnCollectionChange and add test --- apps/examples/cypress/e2e/collection.cy.ts | 21 +++++++++++++++++++++ packages/formiz-core/src/useForm.tsx | 20 +++++++++----------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/apps/examples/cypress/e2e/collection.cy.ts b/apps/examples/cypress/e2e/collection.cy.ts index dd56a8b5..6fc8d7e9 100644 --- a/apps/examples/cypress/e2e/collection.cy.ts +++ b/apps/examples/cypress/e2e/collection.cy.ts @@ -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"); + }); }); diff --git a/packages/formiz-core/src/useForm.tsx b/packages/formiz-core/src/useForm.tsx index 3cb5a125..d4eb572a 100644 --- a/packages/formiz-core/src/useForm.tsx +++ b/packages/formiz-core/src/useForm.tsx @@ -68,19 +68,17 @@ export const useForm = ( export const useOnCollectionsChange = ( useStore?: UseBoundStore> ) => { - const timeoutRef = useRef(); 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; }); };