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

Awaiting for mutation promise makes error and data undefined. #12242

Open
Grsz opened this issue Dec 23, 2024 · 1 comment
Open

Awaiting for mutation promise makes error and data undefined. #12242

Grsz opened this issue Dec 23, 2024 · 1 comment
Labels
🏓 awaiting-contributor-response requires input from a contributor ℹ needs-more-info Needs more information to determine root cause

Comments

@Grsz
Copy link

Grsz commented Dec 23, 2024

If we have const [mutate, { data, error }] = useMutation(), and call mutate() alone, data, and error are populated as expected.

However, when awaiting the result of mutate like mutate().then(() => {}), data, and error are undefined.

I wouldn't expect this behaviour, and cannot seem to find it documented anywhere.

@phryneas
Copy link
Member

phryneas commented Jan 6, 2025

Hi @Grsz,

we might need some more information here, so it would be great if you could share some more code.

That said, if your code snippet looks something like

const [mutate, { data, error }] = useMutation()

mutate().then(() => {
  console.log(data)
})

this is not a problem specific to Apollo Client - you are running into a stale closure:

Your .then function tries to access data of the scope that existed when the function was called. data here is a constant that will never update. Instead, on the next render, a new variable named data will exist in a different scope with a different value. That variable can never be accessed from that "old callback" that you defined with .then as it exists completely independently at a different point in time.

This is not an Apollo Client problem, it is a very common in React apps in general - in this case, if you need access to the new data, you will have to access the arguments passed into your .then function.

@jerelmiller jerelmiller added ℹ needs-more-info Needs more information to determine root cause 🏓 awaiting-contributor-response requires input from a contributor labels Jan 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🏓 awaiting-contributor-response requires input from a contributor ℹ needs-more-info Needs more information to determine root cause
Projects
None yet
Development

No branches or pull requests

3 participants