Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

prevent cancelation of submit when fetcher is unmounted

Roman Pominovd02d71d039e3
diff --git a/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx b/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx
index 19f895cbcb..6cd1b8a2de 100644
--- a/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/panels/pages/settings.tsx
@@ -15,10 +15,11 @@ import { ChevronDoubleLeftIcon, TrashIcon } from "@webstudio-is/icons";
import { utils as projectUtils } from "@webstudio-is/project";
import type { ZodError } from "zod";
import { Header } from "../../lib/header";
-import { useEffect, useRef, useState, useCallback } from "react";
+import { useRef, useState, useCallback } from "react";
import { type Page } from "@webstudio-is/project";
import { usePages } from "~/designer/shared/nano-states";
import { useDebounce, useUnmount } from "react-use";
+import { useOnFetchEnd, usePersistentFetcher } from "~/shared/fetcher";
const Group = styled(Flex, {
marginBottom: "$3",
@@ -30,6 +31,13 @@ type FetcherData<Payload> =
| ({ ok: true } & Payload)
| { errors: string | ZodError["formErrors"] };
+const normalizeErrors = (
+ errors: string | ZodError["formErrors"]
+): ZodError["formErrors"] =>
+ typeof errors === "string"
+ ? { formErrors: [errors], fieldErrors: {} }
+ : errors;
+
type EditablePage = Omit<Page, "treeId" | "id">;
const FormFields = ({
@@ -59,11 +67,7 @@ const FormFields = ({
useOnFetchEnd(fetcher, (data) => {
if ("errors" in data) {
- const errors =
- typeof data.errors === "string"
- ? { formErrors: [data.errors], fieldErrors: {} }
- : data.errors;
-
+ const errors = normalizeErrors(data.errors);
toastNonFieldErrors(errors, fieldNames.current);
setFieldErrors(errors.fieldErrors);
}
@@ -189,6 +193,8 @@ export const PageSettings = ({
pageId: string;
projectId: string;
}) => {
+ const submitPersistently = usePersistentFetcher();
+
const fetcher = useFetcher<EditPageData>();
const [pages] = usePages();
@@ -210,29 +216,44 @@ export const PageSettings = ({
[]
);
- const submit = () => {
- if (Object.keys(unsavedValues).length === 0) {
- return;
- }
-
- // We're re-submitting the submittedValues because previous submit is going to be cancelled
- // (normally, submittedValues are empty at this point)
- const valuesToSubmit = { ...submittedValues, ...unsavedValues };
+ useDebounce(
+ () => {
+ if (Object.keys(unsavedValues).length === 0) {
+ return;
+ }
- fetcher.submit(toFormData({ id: pageId, ...valuesToSubmit }), {
- method: "post",
- action: `/rest/pages/${projectId}`,
- });
+ // We're re-submitting the submittedValues because previous submit is going to be cancelled
+ // (normally, submittedValues are empty at this point)
+ const valuesToSubmit = { ...submittedValues, ...unsavedValues };
- setSubmittedValues(valuesToSubmit);
- setUnsavedValues({});
- };
+ fetcher.submit(toFormData({ id: pageId, ...valuesToSubmit }), {
+ method: "post",
+ action: `/rest/pages/${projectId}`,
+ });
- useDebounce(submit, 1000, [unsavedValues]);
+ setSubmittedValues(valuesToSubmit);
+ setUnsavedValues({});
+ },
+ 1000,
+ [unsavedValues]
+ );
- // @todo: this works by accident,
- // we're abusing a bug in Remix where you can submit a fetcher that was already deleted
- useUnmount(submit);
+ useUnmount(() => {
+ if (Object.keys(unsavedValues).length === 0) {
+ return;
+ }
+ // We use submitPersistently instead of fetcher.submit
+ // because we don't want the request to be canceled when the component unmounts
+ submitPersistently<EditPageData>(
+ toFormData({ id: pageId, ...submittedValues, ...unsavedValues }),
+ { method: "post", action: `/rest/pages/${projectId}` },
+ (data) => {
+ if ("errors" in data) {
+ toastNonFieldErrors(normalizeErrors(data.errors), []);
+ }
+ }
+ );
+ });
useOnFetchEnd(fetcher, (data) => {
if ("errors" in data) {
@@ -241,13 +262,17 @@ export const PageSettings = ({
setSubmittedValues({});
});
- const deleteFetcher = useFetcher<DeletePageData>();
const hanldeDelete = () => {
- // @todo: this doesn't work because when component is unmounted,
- // the fetcher is deleted and the request is cancelled
- deleteFetcher.submit(
+ // We use submitPersistently instead of fetcher.submit
+ // because we don't want the request to be canceled when the component unmounts
+ submitPersistently<DeletePageData>(
{ id: pageId },
- { method: "delete", action: `/rest/pages/${projectId}` }
+ { method: "delete", action: `/rest/pages/${projectId}` },
+ (data) => {
+ if ("errors" in data) {
+ toastNonFieldErrors(normalizeErrors(data.errors), []);
+ }
+ }
);
onDeleted?.();
};
@@ -285,23 +310,3 @@ export const PageSettings = ({
</>
);
};
-
-const useOnFetchEnd = <Data,>(
- fetcher: Fetcher<Data>,
- handler: (data: Data) => void
-) => {
- const latestHandler = useRef(handler);
- latestHandler.current = handler;
-
- const prevFetcher = useRef(fetcher);
- useEffect(() => {
- if (
- prevFetcher.current.state !== fetcher.state &&
- fetcher.state === "idle" &&
- fetcher.data !== undefined
- ) {
- latestHandler.current(fetcher.data);
- }
- prevFetcher.current = fetcher;
- }, [fetcher]);
-};
diff --git a/apps/designer/app/root.tsx b/apps/designer/app/root.tsx
index 9013b2cf39..e7e178baa7 100644
--- a/apps/designer/app/root.tsx
+++ b/apps/designer/app/root.tsx
@@ -4,12 +4,15 @@ import { Outlet } from "@remix-run/react";
import { withSentryRouteTracing } from "@sentry/remix";
import { ErrorBoundary } from "@sentry/remix";
import { OutletProps } from "react-router-dom";
+import { PersistentFetcherProvider } from "./shared/fetcher";
const RootWithErrorBoundary = (props: OutletProps) => (
// @ts-expect-error 'ErrorBoundary' cannot be used as a JSX component.
<ErrorBoundary>
<TooltipProvider>
- <Outlet {...props} />
+ <PersistentFetcherProvider>
+ <Outlet {...props} />
+ </PersistentFetcherProvider>
</TooltipProvider>
</ErrorBoundary>
);
diff --git a/apps/designer/app/shared/fetcher/index.ts b/apps/designer/app/shared/fetcher/index.ts
new file mode 100644
index 0000000000..2e118759f7
--- /dev/null
+++ b/apps/designer/app/shared/fetcher/index.ts
@@ -0,0 +1,2 @@
+export * from "./on-fetch-end";
+export * from "./persistent-fetcher";
diff --git a/apps/designer/app/shared/fetcher/on-fetch-end.ts b/apps/designer/app/shared/fetcher/on-fetch-end.ts
new file mode 100644
index 0000000000..d443eeae97
--- /dev/null
+++ b/apps/designer/app/shared/fetcher/on-fetch-end.ts
@@ -0,0 +1,22 @@
+import { Fetcher } from "@remix-run/react";
+import { useEffect, useRef } from "react";
+
+export const useOnFetchEnd = <Data>(
+ fetcher: Fetcher<Data>,
+ handler: (data: Data) => void
+) => {
+ const latestHandler = useRef(handler);
+ latestHandler.current = handler;
+
+ const prevFetcher = useRef(fetcher);
+ useEffect(() => {
+ if (
+ prevFetcher.current.state !== fetcher.state &&
+ fetcher.state === "idle" &&
+ fetcher.data !== undefined
+ ) {
+ latestHandler.current(fetcher.data);
+ }
+ prevFetcher.current = fetcher;
+ }, [fetcher]);
+};
diff --git a/apps/designer/app/shared/fetcher/persistent-fetcher.tsx b/apps/designer/app/shared/fetcher/persistent-fetcher.tsx
new file mode 100644
index 0000000000..a4d173ccfa
--- /dev/null
+++ b/apps/designer/app/shared/fetcher/persistent-fetcher.tsx
@@ -0,0 +1,82 @@
+import { type FetcherWithComponents, useFetcher } from "@remix-run/react";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useRef,
+ type ReactNode,
+} from "react";
+import { useOnFetchEnd } from "./on-fetch-end";
+
+/* This utility is designed for the case when you want to send a request using Remix's fetcher,
+ * but you don't want the request to be cancelled when the component where useFetcher() is called unmounts.
+ */
+
+type Task<Data> = {
+ target: Parameters<FetcherWithComponents<Data>["submit"]>[0];
+ options: Parameters<FetcherWithComponents<Data>["submit"]>[1];
+ callback?: (data: Data) => void;
+};
+
+type AddTaskFn = <Data>(
+ target: Task<Data>["target"],
+ options: Task<Data>["options"],
+ callback?: Task<Data>["callback"]
+) => void;
+
+const Context = createContext<AddTaskFn | undefined>(undefined);
+
+export const PersistentFetcherProvider = ({
+ children,
+}: {
+ children: ReactNode;
+}) => {
+ const fetcher = useFetcher();
+ const queue = useRef<Task<unknown>[]>([]);
+ const currentRequestCallback = useRef<
+ ((data: unknown) => void) | undefined
+ >();
+
+ useOnFetchEnd(fetcher, (data) => {
+ if (currentRequestCallback.current) {
+ currentRequestCallback.current(data);
+ currentRequestCallback.current = undefined;
+ }
+
+ const nextTask = queue.current.shift();
+
+ if (nextTask) {
+ currentRequestCallback.current = nextTask.callback;
+ fetcher.submit(nextTask.target, nextTask.options);
+ }
+ });
+
+ const addTask = useCallback(
+ (
+ target: Task<unknown>["target"],
+ options: Task<unknown>["options"],
+ callback: Task<unknown>["callback"]
+ ) => {
+ const task: Task<unknown> = { target, options, callback };
+ if (fetcher.state === "idle" && queue.current.length === 0) {
+ currentRequestCallback.current = task.callback;
+ fetcher.submit(task.target, task.options);
+ } else {
+ queue.current.push(task);
+ }
+ },
+ [fetcher]
+ ) as AddTaskFn;
+
+ return <Context.Provider value={addTask}>{children}</Context.Provider>;
+};
+
+export const usePersistentFetcher = () => {
+ const addTask = useContext(Context);
+ if (!addTask) {
+ throw new Error(
+ "usePersistentFetcher is used without PersistentFetcherProvider"
+ );
+ }
+ return addTask;
+};
diff --git a/packages/project/src/db/build.ts b/packages/project/src/db/build.ts
index d1cb447778..57b251ea10 100644
--- a/packages/project/src/db/build.ts
+++ b/packages/project/src/db/build.ts
@@ -136,6 +136,7 @@ export const editPage = async (
};
export const deletePage = async (buildId: Build["id"], pageId: Page["id"]) => {
+ // @todo: delete tree etc.
return updatePages(buildId, async (currentPages) => {
if (pageId === currentPages.homePage.id) {
throw new Error("Cannot delete home page");