Unnecessary network request with default variable values
Intended outcome: A single network request when a graphql component receives new props but the variables are the same.
Actual outcome:
Two network requests are made because the variables calculation on initialization differs from calculation on updateQuery.
When the component is first mounted and initialized, Query.queryObservable.variables contains All of the variables for the query, the ones that are not specified via props are set to their default values.
However, when Query.updateQuery runs it sets the variables to just those defined via props. A new network request is made because this creates an inequality at the object level for previous and new variables, however logically they are the same since the missing variables will use the default values.
How to reproduce the issue:
I wrote a simple reproduction example here: https://codesandbox.io/s/jnrv4ykkzv, where you can see in the network tab that the first request provides values for all 3 variables while the second request provides just the 2 variables specified in the component.
I wish I could open a PR along with the request but after trying a few things I was unable to get this working correctly and I don't have the time to debug further. To work around this you can just specify values for all of the variables in the query.
Version
I'll take a look at this in the upcoming days, does this cause an issue in your cache as well or just some screen flicker?
There doesn't seem to be a cache issue for us. In my use case it isn't even making the screen flicker since the results are exactly the same and we render any results we have even when loading, however it could definitely cause flickers in other use-cases.
This issue just emerged in our codebase. It's more of a problem for us because we have a component whose (simplified) render looks like this:
<Query query={MY_QUERY} variables={this.getVariables()}>
{({ loading, data, error }) => {
if (error) return 'Error'
if (loading) return 'Loading...'
return (
<form>
...
<input value={this.state.value} onChange={this.onChange} />
...
</form>
)
}}
</Query>
MY_QUERY has default values for its variables. With the issue of ObservableQuery.setVariables() comparing variables (pre-processed) against this.variables (post-processed with default values merged in), the Query component makes a network call after every onChange event in the form.
@lamflam's workaround works for us as well; I just figured I'd let anyone who sees this issue know that someone else had the same problem. Thanks apollo team for the awesome platform 🙌
React Apollo has been refactored to use React Hooks behind the scenes for everything, which means a lot has changed since this issue was opened (and a lot of outstanding issues have been resolved). We'll close this issue off, but please let us know if you're still encountering this problem using React Apollo >= 3.1.0. Thanks!