Skip to content

Commit 262380d

Browse files
thomasballingerConvex, Inc.
authored and
Convex, Inc.
committed
Revert "Revert "Block async opt update handlers at compile time" (#37701)" (#37809)
TypeScript protection against using async functions with `withOptimisticupdate` since these callbacks need to be sync to work correctly. GitOrigin-RevId: 3b875e0791214f284fef2547aaf7455c4f158061
1 parent 8b16d30 commit 262380d

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/react/client.test.tsx

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
22
* @vitest-environment happy-dom
33
*/
4-
import { test, expect, describe } from "vitest";
4+
import { test, expect, describe, vi } from "vitest";
55
import ws from "ws";
66

77
import { ConvexReactClient, createMutation, useQuery } from "./client.js";
@@ -112,6 +112,22 @@ describe("useQuery", () => {
112112
);
113113
expect(result.current).toStrictEqual(undefined);
114114
});
115+
116+
test("Optimistic update handlers can’t be async", () => {
117+
const client = testConvexReactClient();
118+
const mutation = createMutation(
119+
anyApi.myMutation.default,
120+
client,
121+
// @ts-expect-error
122+
).withOptimisticUpdate(async () => {});
123+
124+
// Calling the mutation should warn in the console
125+
const consoleWarnSpy = vi.spyOn(console, "warn");
126+
void mutation();
127+
expect(consoleWarnSpy).toHaveBeenCalledWith(
128+
"Optimistic update handler returned a Promise. Optimistic updates should be synchronous.",
129+
);
130+
});
115131
});
116132

117133
// Intentionally disabled because we're only testing types

src/react/client.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,11 @@ export interface ReactMutation<Mutation extends FunctionReference<"mutation">> {
6868
*
6969
* @public
7070
*/
71-
withOptimisticUpdate(
72-
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>,
71+
withOptimisticUpdate<T extends OptimisticUpdate<FunctionArgs<Mutation>>>(
72+
optimisticUpdate: T &
73+
(ReturnType<T> extends Promise<any>
74+
? "Optimistic update handlers must be synchronous"
75+
: {}),
7376
): ReactMutation<Mutation>;
7477
}
7578

0 commit comments

Comments
 (0)