Dependent Queries: type of 'enabled' parameters #4588
-
Hey everyone, I find myself using dependent queries quite a bit, and I'm running into an issue of forcing the types of the enabled parameters to be not null (not null assertion '!' or using 'as') in the query fn. Here is an example:
What is the best approach to this? If the variable is required in the enabled option, shouldn't the type of the variable in the query fn inherit the not null type? I appreciate any input on approaching this problem. I hate forcing a not null or using 'as' when I know TS is smart enough to handle it. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
Have a look here: https://tkdodo.eu/blog/react-query-and-type-script#type-safety-with-the-enabled-option |
Beta Was this translation helpful? Give feedback.
-
My pattern is a little stylistically different from the provided article so I thought I'd provide it here. I simply define the export const useAddressQuery_VoteRecord = (
programId?: PublicKey,
proposalAddress?: PublicKey,
tokenOwnerRecordAddress?: PublicKey
) => {
const enabled =
programId !== undefined &&
proposalAddress !== undefined &&
tokenOwnerRecordAddress !== undefined
return useQuery({
queryKey: enabled
? [
'VoteRecordAddress',
[programId, proposalAddress, tokenOwnerRecordAddress],
]
: undefined,
queryFn: () => {
if (!enabled) throw new Error()
return getVoteRecordAddress(
programId,
proposalAddress,
tokenOwnerRecordAddress
)
},
enabled,
// Staletime is zero by default, so queries get refetched often. PDAs will never go stale.
staleTime: Number.MAX_SAFE_INTEGER,
})
} |
Beta Was this translation helpful? Give feedback.
-
Can't we omit the duplication between import { PendingQuery, useQuery } from 'react-query'
useQuery({
queryKey: [
'VoteRecordAddress',
[programId, proposalAddress, tokenOwnerRecordAddress],
],
queryFn: () => {
if (
programId === undefined ||
proposalAddress === undefined ||
tokenOwnerRecordAddress === undefined ||
) return new PendingQuery();
return getVoteRecordAddress(
programId,
proposalAddress,
tokenOwnerRecordAddress
)
},
// ❤️ `enabled` is no longer necessary
})
// or
import { PendingQueryError, useQuery } from 'react-query'
useQuery({
queryKey: [
'VoteRecordAddress',
[programId, proposalAddress, tokenOwnerRecordAddress],
],
queryFn: () => {
if (
programId === undefined ||
proposalAddress === undefined ||
tokenOwnerRecordAddress === undefined ||
) throw new PendingQueryError();
return getVoteRecordAddress(
programId,
proposalAddress,
tokenOwnerRecordAddress
)
},
}) |
Beta Was this translation helpful? Give feedback.
Have a look here: https://tkdodo.eu/blog/react-query-and-type-script#type-safety-with-the-enabled-option