Replies: 1 comment
-
it doesn't seem doable because we have to create an observer internally, and we need a key to subscribe to. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
TLDR; It would be convenient and provide better type safety if you could toggle the query by providing a falsy value to the
useQuery
function.This might have been up for discussion before, but I search both the issues in the repo and in the discussion here and I couldn't really find anything.
Background
With the
useQuery
hook you can toggle queries by using theenabled
property. This is very useful when you have queries that are dependent on some other query. We've used it with some success, but it has a caveat: it doesn't play nice with typescript.An example from our domain: we have a page where you can display results of a load test. On that page we want to display information about those particular results (which we call a test run), but also about the test that was run. In order to load the test, we first need to load the test run to get the
testId
, and only then can we load the test. And it's only after we've loaded both that we want to display anything.A simplified version of our code looks like this:
Notice how we need to use the
!
-operator in thequeryFn
ofuseTest
to tell typescript that everything's ok. While a developer can tell thatid
won't be undefined whenqueryFn
executes, typescript can't.One question that arises is what should the
queryKey
be ifid
is undefined? The fact thatid
can be undefined also makes it hard to work with other options:placeholderData
,initialData
,onSuccess
, etc. In each of these you have to keep checking ifid
is undefined.And the problem gets worse when the conditions for enabling the query get more complex:
These conditions can't be lifted out into functions while still retaining type safety.
Proposal
I encountered one of these use-cases during work today and a thought struck me: what if I could pass a falsy value to the
useQuery
hook and that toggled the query?Typescript gladly accepts this. I could use more complex conditions without repetition, while still retaining type safety. But more important it is a very convenient (and, if I may say so, nice looking) way of toggling the query.
I have very little knowledge about the inner workings of react-query, but I suppose that it would default to some noop-options if the options passed were falsy.
Beta Was this translation helpful? Give feedback.
All reactions