onError and onCompleted callbacks do not work in useQuery hook
See original GitHub issueIntended 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:
-
Reload the page, notice that there is ‘completed’ word in browser developer console
-
wait for 10 seconds according to the pollInterval
-
notice that there is a new network request, but no console output
-
click ‘Refetch’ button to explicitly call refetch function
-
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:
- Created 2 years ago
- Reactions:4
- Comments:18 (3 by maintainers)
Top GitHub Comments
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!
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.