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.

Attempt to fix useFetch for all our trpc calls (#1948)

Oleg Isonen3885b86f89df
diff --git a/apps/builder/app/dashboard/projects/project-dialogs.tsx b/apps/builder/app/dashboard/projects/project-dialogs.tsx
index 2c63e6d288..3445e422f1 100644
--- a/apps/builder/app/dashboard/projects/project-dialogs.tsx
+++ b/apps/builder/app/dashboard/projects/project-dialogs.tsx
@@ -95,41 +95,9 @@ const trpc = createTrpcRemixProxy<DashboardProjectRouter>(dashboardProjectPath);
const useCreateProject = () => {
const navigate = useNavigate();
- const { send, data, state } = trpc.create.useMutation();
+ const { send, state } = trpc.create.useMutation();
const [errors, setErrors] = useState<string>();
- // There's an occasional issue where React skips `useEffect(, [data])`, possibly due to a race condition.
- // To frequently replicate this issue:
- // 1. Create 20 projects
- // 2. Turn on CPU 6x slowdown in Chrome dev tools
-
- // Upon creating a new project, you'll find that it doesn't redirect to the new project page.
- // The problem is that `useEffect` with either `data` or `data?.id` as a dependency is not triggered.
-
- // Some working fixes:
- // 1. Non-remix fetch - using createTrpcFetchProxy
- // 2. Use this code inside useEffect:
- // if (ref.current !== data?.projectId) { doRedirect(); }; ref.current = data?.projectId;
- // 3. Use useState as shown below
- //
- // Some observations:
- // The issue seems related to the amount of rendering, possibly due to concurrent React's features.
- // It's also related to Remix's useFetcher, which may be using setState or something similar
- // in a way that's not compatible with concurrent React.
-
- const [projectId, setProjectId] = useState<DashboardProject["id"]>();
-
- if (projectId !== data?.id) {
- setProjectId(data?.id);
- }
-
- useEffect(() => {
- if (projectId === undefined) {
- return;
- }
- navigate(builderPath({ projectId }));
- }, [projectId, navigate]);
-
const handleSubmit = ({ title }: { title: string }) => {
const parsed = Title.safeParse(title);
const errors =
@@ -138,7 +106,11 @@ const useCreateProject = () => {
: undefined;
setErrors(errors);
if (parsed.success) {
- send({ title });
+ send({ title }, (data) => {
+ if (data?.id) {
+ navigate(builderPath({ projectId: data.id }));
+ }
+ });
}
};
@@ -156,6 +128,7 @@ const useCreateProject = () => {
export const CreateProject = () => {
const { handleSubmit, handleOpenChange, state, errors } = useCreateProject();
+
return (
<Dialog
title="New Project"
diff --git a/apps/builder/app/shared/remix/trpc-remix-proxy.ts b/apps/builder/app/shared/remix/trpc-remix-proxy.ts
index d9e6eafb5b..286187d11a 100644
--- a/apps/builder/app/shared/remix/trpc-remix-proxy.ts
+++ b/apps/builder/app/shared/remix/trpc-remix-proxy.ts
@@ -7,7 +7,7 @@ import type {
} from "@trpc/server";
// eslint-disable-next-line import/no-internal-modules
import { createRecursiveProxy } from "@trpc/server/shared";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
export const createTrpcRemixProxy = <Router extends AnyRouter>(
getPath: (method: string) => string
@@ -15,14 +15,20 @@ export const createTrpcRemixProxy = <Router extends AnyRouter>(
[Procedure in keyof Router["_def"]["record"]]: Router["_def"]["record"][Procedure] extends AnyMutationProcedure
? {
useMutation: () => {
- send: (input: inferRouterInputs<Router>[Procedure]) => void;
+ send: (
+ input: inferRouterInputs<Router>[Procedure],
+ onSuccess?: (data: inferRouterOutputs<Router>[Procedure]) => void
+ ) => void;
data?: inferRouterOutputs<Router>[Procedure];
state: "idle" | "loading" | "submitting";
};
}
: {
useQuery: () => {
- load: (input: inferRouterInputs<Router>[Procedure]) => void;
+ load: (
+ input: inferRouterInputs<Router>[Procedure],
+ onSuccess?: (data: inferRouterOutputs<Router>[Procedure]) => void
+ ) => void;
data?: inferRouterOutputs<Router>[Procedure];
state: "idle" | "loading" | "submitting";
};
@@ -39,9 +45,39 @@ export const createTrpcRemixProxy = <Router extends AnyRouter>(
const method = path.join(".");
+ const previousDataRef = useRef(data);
+ const onSuccessRef = useRef<(data: unknown) => void>();
+
+ // There's an occasional issue where React skips `useEffect(, [data])`, possibly due to a race condition.
+ // To frequently replicate this issue:
+ // 1. Open dashboard
+ // 1. Create 20 projects
+ // 2. Turn on CPU 6x slowdown in Chrome dev tools
+
+ // Upon creating a new project, you'll find that it doesn't redirect to the new project page if dependency doesn't contain `state`.
+ // The problem is that `useEffect` with only `data` or `data?.id` as a dependency is not triggered.
+
+ // Some working fixes:
+ // 1. Non-remix fetch - using createTrpcFetchProxy
+ // 2. Use this code inside useEffect:
+ // if (ref.current !== data?.projectId) { doRedirect(); }; ref.current = data?.projectId;
+ // 3. Use useState as shown below
+ //
+ // Some observations:
+ // The issue seems related to the amount of rendering, possibly due to concurrent React's features.
+ // It's also related to Remix's useFetcher, which may be using setState or something similar
+ // in a way that's not compatible with concurrent React.
+ useEffect(() => {
+ if (data !== previousDataRef.current) {
+ previousDataRef.current = data;
+ onSuccessRef.current?.(data);
+ }
+ }, [data, state]);
+
const remixSubmit = useCallback(
- (input: never) => {
- return submit(
+ (input: never, onSuccess: (data: unknown) => void) => {
+ onSuccessRef.current = onSuccess;
+ submit(
// stringify input as otherwise we loose type safety
// (remix will add key: values as FormData entries or as SearchParams
{ input: JSON.stringify(input) },
diff --git a/apps/builder/app/shared/share-project/share-project-container.tsx b/apps/builder/app/shared/share-project/share-project-container.tsx
index 8aac477d18..7927fcf2e0 100644
--- a/apps/builder/app/shared/share-project/share-project-container.tsx
+++ b/apps/builder/app/shared/share-project/share-project-container.tsx
@@ -16,17 +16,12 @@ const useShareProjectContainer = (projectId: Project["id"]) => {
const { send: removeToken } = trpc.remove.useMutation();
const { send: updateToken } = trpc.update.useMutation();
const [links, setLinks] = useState(data ?? []);
- useEffect(() => {
- if (projectId === undefined) {
- return;
- }
-
- load({ projectId });
- }, [load, projectId]);
useEffect(() => {
- setLinks(data ?? []);
- }, [data, setLinks]);
+ load({ projectId }, (data) => {
+ setLinks(data ?? []);
+ });
+ }, [load, projectId]);
const handleChangeDebounced = useDebouncedCallback((link: LinkOptions) => {
if (projectId === undefined) {