apollo-client: onCompleted doesn't have the expected scope

Hi, I’m using apollo/client": “3.6.8” The issue I have is when I’m trying to use a function inside onCompleted of useQuery I’m having the error: Uncaught ReferenceError: Cannot access 'myFunction' before initialization

For example:

const { data }: any = useQuery<MyQueryResult>(MyDocument, {
   onCompleted: (e) => myFunction()
})

const myFunction = () => ....

to solve it I need to move myFunction on top of useQuery, Is it new expected behavior or a bug?

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 16 (14 by maintainers)

Most upvoted comments

Not sure if this will fix the issue, but give v3.7 a try. PR #9801 made a small change to the time when onCompleted gets called, so there’s a chance it might help.

@jpvajda Can we re-open this issue, as the original problem has not yet been resolved? 😃

I’m seeing the same issue as @wuarmin: When I try to update state in my onCompleted callback, the state update is reverted on the next render. This only happens when the result comes from the cache: If it is fresh, it doesn’t happen.

Hey, I’m still on react 17 and have a very weird issue with useLazyQuery in combination with cache-first and onCompleted. I think this issue could be related.

If the query result is already in cache the onCompleted callback seems to be called, but if I use the response data to set some state with setState in the callback, the component does not rerender. If the query loads data, not in cache, it works.

I’m trying to dive deeper in this issue, but I struggled with it the whole day today😭 @jpvajda The apollo-client-error-template-codesandbox seems not to work, nothing shows up, but I don’t see errors. Is it working for you? https://codesandbox.io/s/github/apollographql/react-apollo-error-template

Let me know, if you need further infos. I am very interested in solving the problem. Thanks

@jpvajda the codesandbox error template is broken for me too (tried in chrome, firefox, firefox dev edition. all broken). These changes seem to fix it for me:

  • Rename index.jsx to index.js
  • Downgrade the graphql package to 15.8.0

It started only after i upgraded to react v18