I've re-read the doc, I think this is a bug. The whole point of useLazyQuery is executing queries in response to events other than component rendering, but this is what exactly happens when we change the query variables - we make a network call every single render (in case of only-network or cache-and-network policies).
Thoughts @benjamn? Not sure what to do with it.
If you pass the variables when you use the function to call the query instead of setting them on the query itself this won't happen.
It doesn't make sense for updating the variables inside the query to do this. Most people would expect either method to only execute the query when the function is called.
demonstration of the query executing on every render
(variables set on instantiation): https://codesandbox.io/s/vigorous-forest-8609l
demonstration of the query only executing on function call
(variables set on call): https://codesandbox.io/s/bold-platform-jk2wo
Thanks for the alternative solution @Relsig. @alexpermyakov I'm new to Apollo, so naturally I thought I missed something...came across this after trying to debug for too long. Nice to know I'm not the only one!
@pmcorrea
I also spend lot of time time on this issue, I am new to apollo. Either we need to add this to doc or need to make a fix. I will check if I can do something on this.
@Relsig thanks for sharing a quick solution.
As per this line, the query will be executed again if any of the options
passed to the useLazyQuery
hook changes. This behaviour is same for useLazyQuery
and useQuery
.
I think we can do any one of the below to close this issue:
options
passed changes in the case of useLazyQuery
. The query will be executed again if any of the
options
passed to theuseLazyQuery
hook changes. This behaviour is same foruseLazyQuery
anduseQuery
.
The problem with this 1st solution is that it might break somebody's code. So I think it is better to add the sentence to the doc.
I will raise a pr with the change.
Since the whole point of useLazyQuery
is to have better control over when exactly the query runs, I think this behavior should be changed to better match user expectations, personally.
Most helpful comment
If you pass the variables when you use the function to call the query instead of setting them on the query itself this won't happen.
It doesn't make sense for updating the variables inside the query to do this. Most people would expect either method to only execute the query when the function is called.
demonstration of the query executing on every render
(variables set on instantiation): https://codesandbox.io/s/vigorous-forest-8609l
demonstration of the query only executing on function call
(variables set on call): https://codesandbox.io/s/bold-platform-jk2wo