question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

onError and onCompleted callbacks do not work in useQuery hook

See original GitHub issue

Intended outcome: onCompleted or onErorr callbacks should be called on refetch or polling in useQuery hook, according to the documentation https://www.apollographql.com/docs/react/api/react/hooks/

Actual outcome: onCompleted called only once at initial render, onErorr not called

How to reproduce the issue:

  1. Reload the page, notice that there is ‘completed’ word in browser developer console

  2. wait for 10 seconds according to the pollInterval

  3. notice that there is a new network request, but no console output

  4. click ‘Refetch’ button to explicitly call refetch function

  5. set network to offline mode in browser developer tools, wait for 10 seconds or click refetch button and see that no onError callback fired.

import ReactDOM from 'react-dom';

import { ApolloClient, ApolloProvider, gql, InMemoryCache, useQuery } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache()
});

const QUERY = gql`
query GetRates {
  rates(currency: "USD") {
    currency
    rate
  }
}
`

function App() {
  const [count, setCount] = useState(0);

  const { refetch, data } = useQuery(QUERY, {
    fetchPolicy:'network-only',
    pollInterval: 10 * 1000,
    onCompleted: () => {
      setCount(count+1);
      console.log('completed')
    },
    onError: () => {
      setCount(count+1);
      console.log('error')
    },
  })
  
  const clickCallback = useCallback(()=>{
    refetch();
  }, [refetch]);

  return (
    <div className="App">
      Apollo callbacks count  {count}

      <button onClick={clickCallback}>Refetch</button>
      <div>{JSON.stringify(data)}</div>
    </div>
  );
}


ReactDOM.render(
  <React.StrictMode>
   <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  </React.StrictMode>,
  document.getElementById('root')
);

Versions

“dependencies”: { “@apollo/client”: “^3.3.19”, “@testing-library/jest-dom”: “^5.11.4”, “@testing-library/react”: “^11.1.0”, “@testing-library/user-event”: “^12.1.10”, “@types/jest”: “^26.0.15”, “@types/node”: “^12.0.0”, “@types/react”: “^17.0.0”, “@types/react-dom”: “^17.0.0”, “graphql”: “^15.5.0”, “react”: “^17.0.2”, “react-dom”: “^17.0.2”, “react-scripts”: “4.0.3”, “typescript”: “^4.1.2”, “web-vitals”: “^1.0.1” },

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:4
  • Comments:18 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
alanxpcommented, May 30, 2021

I thought i was the only one with this problem!,

the “onError” callback only shows this {"graphQLErrors":[],"networkError":{},"message":"Failed to fetch"}

and it wont let me know if it’s a networkError or graphQLErrors because both Object and Array are Empty!

3reactions
tonycassaracommented, Oct 26, 2021

Confirming that https://github.com/apollographql/react-apollo/issues/3709#issuecomment-592786578 solved my issue. This should be more clear in the docs. Might open a PR later.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Any benefit of using onError and onCompleted callbacks ...
I have a component using apollo-client with react where I was originally using the onError and onCompleted callbacks to set data once it...
Read more >
Hooks - Apollo GraphQL Docs
A callback function that's called when your query successfully completes with zero errors (or if errorPolicy is ignore and partial data is returned)....
Read more >
useQuery | TanStack Query Docs
A function to manually refetch the query. · If the query errors, the error will only be logged. If you want an error...
Read more >
The React + Apollo Tutorial for 2020 (Real-World Examples)
The useQuery hook is arguably the most convenient way of performing a GraphQL query, considering that it doesn't return a promise that needs ......
Read more >
Use-safe-query NPM | npm.io
Implementation to adapt useQuery to use both errors and data callbacks easily ... but this way onError is not fired (so we can't...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found