diff --git a/.changeset/pretty-maps-smash.md b/.changeset/pretty-maps-smash.md new file mode 100644 index 0000000..f989f9b --- /dev/null +++ b/.changeset/pretty-maps-smash.md @@ -0,0 +1,5 @@ +--- +"@deadcow-enterprises/react-form-hook": patch +--- + +stop propagation of form submit event diff --git a/.nvmrc b/.nvmrc index 68c98aa..016efd8 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v18.18.2 \ No newline at end of file +v20.10.0 \ No newline at end of file diff --git a/src/hook.test.ts b/src/hook.test.ts index 7fac660..9d3f3f2 100644 --- a/src/hook.test.ts +++ b/src/hook.test.ts @@ -1,7 +1,7 @@ -import { renderHook, act } from "@testing-library/react"; -import { z } from "zod"; +import { act, renderHook } from "@testing-library/react"; import { FormEvent } from "react"; -import { describe, it, expect, vi } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { z } from "zod"; import { useForm } from "./hook"; import { FormError } from "./types"; interface FormType { @@ -214,14 +214,16 @@ describe("Hook", () => { const fn = vi.fn(); - const ev: Pick = { + const ev: Pick = { preventDefault: vi.fn(), + stopPropagation: vi.fn(), }; act(() => { result.current.handleSubmit(fn)(ev as any); }); expect(ev.preventDefault).toBeCalled(); + expect(ev.stopPropagation).toBeCalled(); expect(fn).toBeCalledWith(formInitialValue); }); it("Should run promise callback function on submit", () => { @@ -246,14 +248,16 @@ describe("Hook", () => { const fn = vi.fn>(); - const ev: Pick = { + const ev: Pick = { preventDefault: vi.fn(), + stopPropagation: vi.fn(), }; act(() => { result.current.handleSubmit(fn)(ev as any); }); expect(ev.preventDefault).toBeCalled(); + expect(ev.stopPropagation).toBeCalled(); expect(fn).toBeCalledWith(formInitialValue); }); it("Should not run callback function on submit if there are errors", () => { @@ -289,14 +293,16 @@ describe("Hook", () => { const fn = vi.fn(); - const ev: Pick = { + const ev: Pick = { preventDefault: vi.fn(), + stopPropagation: vi.fn(), }; act(() => { result.current.handleSubmit(fn)(ev as any); }); expect(ev.preventDefault).toBeCalled(); + expect(ev.stopPropagation).toBeCalled(); expect(fn).not.toHaveBeenCalled(); expect(result.current.errors).toStrictEqual({ propertyA: ["Should be X characters long"], diff --git a/src/hook.ts b/src/hook.ts index c6d8d29..1dcdf5b 100644 --- a/src/hook.ts +++ b/src/hook.ts @@ -61,6 +61,7 @@ export function useForm>( }, handleSubmit: (cb) => { return async (ev) => { + ev.stopPropagation(); ev.preventDefault(); const valid = updateValidity(); if (!valid) {