Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onMutate never actually runs synchronously #8724

Open
sleexyz opened this issue Mar 1, 2025 · 3 comments
Open

onMutate never actually runs synchronously #8724

sleexyz opened this issue Mar 1, 2025 · 3 comments

Comments

@sleexyz
Copy link

sleexyz commented Mar 1, 2025

onMutate never actually runs synchronously because the result of #mutationCache.config.onMutate?.() is always awaited beforehand

Diff that fixes this:

diff --git a/node_modules/@tanstack/query-core/build/modern/mutation.js b/node_modules/@tanstack/query-core/build/modern/mutation.js
index 1bc7990..efbddd6 100644
--- a/node_modules/@tanstack/query-core/build/modern/mutation.js
+++ b/node_modules/@tanstack/query-core/build/modern/mutation.js
@@ -82,10 +82,12 @@ var Mutation = class extends Removable {
     try {
       if (!restored) {
         this.#dispatch({ type: "pending", variables, isPaused });
-        await this.#mutationCache.config.onMutate?.(
-          variables,
-          this
-        );
+        if (this.#mutationCache.config.onMutate) {
+          await this.#mutationCache.config.onMutate(
+            variables,
+            this
+          );
+        }
         const context = await this.options.onMutate?.(variables);
         if (context !== this.state.context) {
           this.#dispatch({

(Diff generated via patch-package to patch @tanstack/query-core@5.51.21)

@TkDodo
Copy link
Collaborator

TkDodo commented Mar 3, 2025

We guarantee that onMutate runs synchronously, because it can in itself return a promise. We also await the result of it, it’s in your diff:

const context = await this.options.onMutate?.(variables);

So, no, I don’t think onMutate is meant to be syncronous.

@sleexyz
Copy link
Author

sleexyz commented Mar 3, 2025 via email

@TkDodo
Copy link
Collaborator

TkDodo commented Mar 5, 2025

okay I think the change in the PR doesn’t hurt, so feel free to file it. However, this then means that the behaviour changes depending on if you have an onMutate defined on the mutationCache.

So I really wouldn’t rely on it being synchronous, as this would change as soon as you add onMutate on the cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants