Skip to content

Commit

Permalink
Merge pull request #144 from david-szabo97/fix/submit-action-basename
Browse files Browse the repository at this point in the history
Remove basename from submit target action
  • Loading branch information
AlemTuzlak authored Jan 5, 2025
2 parents bc65d42 + f3c93aa commit a7619e5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
36 changes: 36 additions & 0 deletions src/hook/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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: <explanation>
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;
Expand Down
4 changes: 3 additions & 1 deletion src/hook/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
useActionData,
useNavigation,
useSubmit,
useHref,
} from "react-router";

import { createFormData } from "../utilities";
Expand Down Expand Up @@ -60,6 +61,7 @@ export const useRemixForm = <T extends FieldValues>({
...formProps
}: UseRemixFormOptions<T>) => {
const [isSubmittedSuccessfully, setIsSubmittedSuccessfully] = useState(false);
const basename = useHref("/");
const actionSubmit = useSubmit();
const actionData = useActionData();
const submit = fetcher?.submit ?? actionSubmit;
Expand Down Expand Up @@ -211,7 +213,7 @@ export const useRemixForm = <T extends FieldValues>({
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}`,
"",
);

Expand Down

0 comments on commit a7619e5

Please sign in to comment.