Skip to content

Commit

Permalink
fixup! feat: auto fields management
Browse files Browse the repository at this point in the history
  • Loading branch information
edmundhung committed Oct 1, 2024
1 parent b0d4012 commit c07a223
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
7 changes: 4 additions & 3 deletions packages/conform-dom/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,8 @@ export type FormContext<
onInput(event: Event): void;
onBlur(event: Event): void;
onUpdate(options: Partial<FormOptions<Schema, FormError, FormValue>>): void;
observe(stateSnapshot: FormState<FormError>): () => void;
updateFormElement(state: FormState<FormError>): void;
observe(): () => void;
subscribe(
callback: () => void,
getSubject?: () => SubscriptionSubject | undefined,
Expand Down Expand Up @@ -1119,7 +1120,7 @@ export function createFormContext<
}
}

function observe(stateSnapshot: FormState<FormError>) {
function observe() {
const observer = new MutationObserver((mutations) => {
const form = getFormElement();

Expand Down Expand Up @@ -1155,7 +1156,6 @@ export function createFormContext<
attributes: true,
attributeFilter: ['form', 'name'],
});
updateFormElement(stateSnapshot);

return () => {
observer.disconnect();
Expand All @@ -1177,6 +1177,7 @@ export function createFormContext<
insert: createFormControl('insert'),
remove: createFormControl('remove'),
reorder: createFormControl('reorder'),
updateFormElement,
subscribe,
getState,
getSerializedState,
Expand Down
8 changes: 3 additions & 5 deletions packages/conform-react/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,13 @@ export function useForm<
);

useSafeLayoutEffect(() => {
const disconnect = context.observe();
document.addEventListener('input', context.onInput);
document.addEventListener('focusout', context.onBlur);
document.addEventListener('reset', context.onReset);

return () => {
disconnect();
document.removeEventListener('input', context.onInput);
document.removeEventListener('focusout', context.onBlur);
document.removeEventListener('reset', context.onReset);
Expand All @@ -101,11 +103,7 @@ export function useForm<
const form = getFormMetadata(context, subjectRef, stateSnapshot, noValidate);

useEffect(() => {
const disconnect = context.observe(stateSnapshot);

return () => {
disconnect();
};
context.updateFormElement(stateSnapshot);
}, [context, stateSnapshot]);

return [form, form.getFieldset()];
Expand Down

0 comments on commit c07a223

Please sign in to comment.