Skip to content

Best practices for: useQuery + possibly undefined parameters + strict typescript. #5916

Answered by TkDodo
valerioleo asked this question in General
Discussion options

You must be logged in to vote

yeah, I'm afraid there is no better solution. You can:

  • use the bang operator !. I think Alex from trpc says this is one of the cases where he uses it
  • check it in the queryFn
  • maybe, but I probably wouldn't do it, provide the queryFn conditionally:
  const { data, error } = useQuery({
-    queryFn: () => fetchItem(selectedItem),
+    queryFn: selectedItem ? () => fetchItem(selectedItem) : undefined,
    enabled: !!selectedItem,
    retry: 0
  });

This works on type level, and RQ is fine with it, because queryFn is technically optional (it could be defined globally). But you really have to make sure that that the queryFn doesn't run any other way, or you get a Missing queryFn error.

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
5 replies
@valerioleo
Comment options

@TkDodo
Comment options

Answer selected by valerioleo
@valerioleo
Comment options

@TkDodo
Comment options

@John-Paul-R
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants