Skip to content

Commit

Permalink
fix: update form.collection on collection registration/unregistration
Browse files Browse the repository at this point in the history
  • Loading branch information
HugoPerard committed Sep 23, 2024
1 parent bcf3e27 commit d6db9b3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/formiz-core/src/useForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const useForm = <Values extends object = any>(

useOnValuesChange(useStore);
useIsValidChange(useStore);
useOnCollectionsChange(useStore);

const formActions = useStore(useCallback((state) => state.actions, []));

Expand All @@ -64,6 +65,26 @@ export const useForm = <Values extends object = any>(
return formState;
};

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;
});
return prevCollectionsCountRef.current;
});
};

const useOnValuesChange = (useStore?: UseBoundStore<StoreApi<Store>>) => {
const timeoutRef = useRef<NodeJS.Timeout>();
const prevFormValuesRef = useRef({});
Expand Down
2 changes: 2 additions & 0 deletions packages/formiz-core/src/useFormContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { formInterfaceSelector } from "@/selectors";
import { ERROR_USE_FORM_CONTEXT_MISSING_CONTEXT } from "@/errors";
import { Store, useFormProps } from "@/types";
import { isDeepEqual } from "@/utils/global";
import { useOnCollectionsChange } from "@/useForm";

export const useFormContext = <Values extends object = any>(
options?: Pick<useFormProps<Values>, "stateSubscription">
Expand All @@ -11,6 +12,7 @@ export const useFormContext = <Values extends object = any>(
if (!useStore) {
throw new Error(ERROR_USE_FORM_CONTEXT_MISSING_CONTEXT);
}
useOnCollectionsChange(useStore);
const formState = useStore?.(
(state) =>
formInterfaceSelector<Values>(
Expand Down

0 comments on commit d6db9b3

Please sign in to comment.