onCompleted not called after skip is set to false and the data is cached
See original GitHub issueConsider this code (useQuery
with a skip condition):
const { loading, data } = useQuery(MY_QUERY, {
skip: condition,
onCompleted: response => { /* Handle the response */ },
});
Intended outcome:
onCompleted
should be called after the data has been fetched, either from the server or from the cache.
Actual outcome:
onCompleted
is called only when the data is fetched from the server and not when it is fetched from the cache.
How to reproduce the issue: https://codesandbox.io/s/apollo-query-skip-bug-x60ht (This codesandbox example fetches data from https://graphqlzero.almansi.me/api)
- Click on the Show Page button.
That will mount the
<Page />
component, which contains this code:const { loading, data } = useQuery(USERS_QUERY, { skip: skipper, onCompleted: response => { setUserList(response.users.data); }, }); console.log(data);
You will see the value of
data
in the console output. It isundefined
.
- Click on the Start Fetching button.
That will set the value of
skipper
tofalse
. The query will be executed andonCompleted
will be called. You will see the value ofdata
in the console output. This time it won’t beundefined
. It will be an Object. You will also see the fetched data displayed inside the<Page />
component, and that is because theonCompleted
handler changed the state of the component.
- Click on the Hide Page button.
That will unmount the
<Page />
component
- Click on the Show Page button.
That will mount the
<Page />
component again, and the value ofdata
in the console output isundefined
.
- Click on the Start Fetching button.
This time the query will fetch the data from the cache.
onCompleted
won’t be called, but you can see the value ofdata
in the console output, and it is an Object.
Versions System: OS: Windows 10 10.0.19041 Binaries: Node: 12.18.3 - C:\Program Files\nodejs\node.EXE npm: 6.14.6 - C:\Program Files\nodejs\npm.CMD Browsers: Chrome: 87.0.4280.88 Edge: Spartan (44.19041.423.0), Chromium (87.0.664.66) npmPackages: @apollo/client: ^3.3.6 => 3.3.6 apollo-upload-client: ^14.1.2 => 14.1.2
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:6
Top GitHub Comments
I don’t use
onCompleted
any more. I do it like this now:This is a big problem! It’s breaking the API contract that says the function is going to be called when the fetch completes. This makes our progress bars to hang, and it is ridiculous that Apollo does not abstract us from this. What is the alternative? Some weird timeout functions that automatically clear the state ? I can’t believe nobody else is complaining about this