Skip to content

Commit ab65f3a

Browse files
author
Erik Rasmussen
committed
Address CodeRabbit feedback: use waitFor, cleanup orphan subscription
1 parent 4295d41 commit ab65f3a

File tree

2 files changed

+6
-8
lines changed

2 files changed

+6
-8
lines changed

src/useField.issue-984.test.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
11
import * as React from "react";
2-
import { render, cleanup } from "@testing-library/react";
2+
import { render, waitFor } from "@testing-library/react";
33
import "@testing-library/jest-dom";
44
import Form from "./ReactFinalForm";
55
import { useField } from "./index";
66

77
const onSubmitMock = (_values) => {};
88

99
describe("useField issue #984", () => {
10-
afterEach(cleanup);
11-
1210
// https://github.com/final-form/react-final-form/issues/984
1311
// When a parent component's useEffect changes a form value,
1412
// sibling components' useField should receive the updated value.
@@ -50,10 +48,8 @@ describe("useField issue #984", () => {
5048

5149
// After useEffect runs, Field2 should see the updated value
5250
// This is the bug: Field2 sees stale "InitialField1" instead
53-
await (async () => {
54-
// Wait a bit for effects to settle
55-
await new Promise((resolve) => setTimeout(resolve, 100));
51+
await waitFor(() => {
5652
expect(getByTestId("field1-value").textContent).toBe("UpdatedByField1");
57-
})();
53+
});
5854
});
5955
});

src/useField.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,14 @@ function useField<
238238
try {
239239
// Manually update initialValues via registerField with silent: false
240240
// to force notification
241-
form.registerField(
241+
const unsubscribe = form.registerField(
242242
name as keyof FormValues,
243243
() => {},
244244
{},
245245
{ initialValue }
246246
);
247+
// Immediately unsubscribe to avoid orphan subscriber
248+
unsubscribe();
247249
} finally {
248250
form.resumeValidation();
249251
}

0 commit comments

Comments
 (0)