Fix modal de-registration firing twice (#2145)

Global Modals as components, and as a result their registration hooks, have a lifecycle that spans the whole application. Because of this, they never get unmounted. The registration hook will simply be re-rendered with an updated "active" flag. Because the hook did not reset to its initial state when switching from "active" to "deactive", it decremented the modal count twice. Once in the cleanup of the previous hook render and once in the else block ("inactive").
This commit is contained in:
Konstantin Schaper
2022-11-03 19:17:39 +01:00
committed by GitHub
parent a009ce9397
commit ec83de3600
3 changed files with 20 additions and 2 deletions

View File

@@ -72,7 +72,7 @@ describe("useRegisterModal", () => {
expect(increment).not.toHaveBeenCalled();
});
it("should decrement on active de-registration", () => {
it("should decrement once on active de-registration", () => {
const increment = jest.fn();
const decrement = jest.fn();
@@ -82,7 +82,22 @@ describe("useRegisterModal", () => {
result.unmount();
expect(decrement).toHaveBeenCalled();
expect(decrement).toHaveBeenCalledTimes(1);
expect(increment).not.toHaveBeenCalled();
});
it("should decrement once when switching from active to inactive", () => {
const increment = jest.fn();
const decrement = jest.fn();
const result = renderHook(({ active }: { active: boolean }) => useRegisterModal(active), {
wrapper: createWrapper({ value: 0, increment, decrement }),
initialProps: { active: true },
});
result.rerender({ active: false });
expect(decrement).toHaveBeenCalledTimes(1);
expect(increment).toHaveBeenCalledTimes(1);
});
});

View File

@@ -47,6 +47,7 @@ export default function useRegisterModal(active: boolean, initialValue: boolean
return () => {
if (previousActiveState.current) {
decrement();
previousActiveState.current = null;
}
};
}, [active, decrement, increment]);