diff --git a/src/hook/index.test.tsx b/src/hook/index.test.tsx index af3be3a..bb38cad 100644 --- a/src/hook/index.test.tsx +++ b/src/hook/index.test.tsx @@ -22,11 +22,14 @@ const useNavigationMock = vi.hoisted(() => })), ); +const useHrefMock = vi.hoisted(() => vi.fn()); + vi.mock("react-router", () => ({ useSubmit: () => submitMock, useActionData: useActionDataMock, useFetcher: () => ({ submit: fetcherSubmitMock, data: {} }), useNavigation: useNavigationMock, + useHref: useHrefMock, })); describe("useRemixForm", () => { @@ -149,6 +152,39 @@ describe("useRemixForm", () => { }); }); + it("should remove origin and basename from the action", async () => { + submitMock.mockReset(); + useHrefMock.mockImplementation((to) => { + if (to === "/") { + return "/my-basename"; + } + }); + vi.spyOn(window, "location", "get").mockReturnValueOnce({ + origin: "http://example.com", + } as any); + + const { result } = renderHook(() => + useRemixForm({ + resolver: () => ({ values: {}, errors: {} }), + }), + ); + + act(() => { + // biome-ignore lint/suspicious/noExplicitAny: + result.current.handleSubmit({ + currentTarget: { + action: "http://example.com/my-basename/basename-test-submit", + }, + } as any); + }); + await waitFor(() => { + expect(submitMock).toHaveBeenCalledWith(expect.any(FormData), { + method: "post", + action: "/basename-test-submit", + }); + }); + }); + it("should not re-render on validation if isValidating is not being accessed", async () => { const renderHookWithCount = () => { let count = 0; diff --git a/src/hook/index.tsx b/src/hook/index.tsx index 46eeec0..aba6ace 100644 --- a/src/hook/index.tsx +++ b/src/hook/index.tsx @@ -30,6 +30,7 @@ import { useActionData, useNavigation, useSubmit, + useHref, } from "react-router"; import { createFormData } from "../utilities"; @@ -60,6 +61,7 @@ export const useRemixForm = ({ ...formProps }: UseRemixFormOptions) => { const [isSubmittedSuccessfully, setIsSubmittedSuccessfully] = useState(false); + const basename = useHref("/"); const actionSubmit = useSubmit(); const actionData = useActionData(); const submit = fetcher?.submit ?? actionSubmit; @@ -211,7 +213,7 @@ export const useRemixForm = ({ const encType = e?.currentTarget?.enctype as FormEncType | undefined; const method = e?.currentTarget?.method as FormMethod | undefined; const action = e?.currentTarget?.action.replace( - window.location.origin, + `${window.location.origin}${basename === "/" ? "" : basename}`, "", );