Best practices for: useQuery
+ possibly undefined parameters + strict typescript.
#5916
-
Thanks to all the creators and maintainers of this amazing library. I'm using it since a few months and there is no looking back. However, as my use cased become more advanced, I have some questions about best practices. In particular, how to best handle import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
const fetchItem = async (itemId: string) => {
if (!itemId) {
throw Error("Must pass item id!");
}
return Promise.resolve(`Visualising data from item: ${itemId}!`);
};
export function App() {
const [selectedItem, setSelectedItem] = useState<string>();
const { data, error } = useQuery({
queryFn: () => fetchItem(selectedItem),
enabled: !!selectedItem,
retry: 0
});
return (
<div>
<button onClick={() => setSelectedItem("1")}> Fetch 1 </button>
<button onClick={() => setSelectedItem("2")}> Fetch 2 </button>
<button onClick={() => setSelectedItem("3")}> Fetch 3 </button>
<br />
<br />
<br />
{data ? (
<div>
{data}
<button> Deselect all </button>
</div>
) : (
"Select an item first"
)}
<br />
{error?.message}
</div>
);
}
export default App; In this snippet, the I have noticed that this happens only when I have the Some solutions I have found are:
Is there any other solution I have missed? FYI: here is the codesandbox link for the above example: https://codesandbox.io/s/tanstack-react-query--query-parameters-s9nhqn?file=/src/containers/App/App.tsx |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
I'd change - const fetchItem = async (itemId: string) => {
+ const fetchItem = async (itemId: string | undefined) => {
if (!itemId) {
throw Error("Must pass item id!");
}
return Promise.resolve(`Visualising data from item: ${itemId}!`);
}; see also: https://tkdodo.eu/blog/react-query-and-type-script#type-safety-with-the-enabled-option |
Beta Was this translation helpful? Give feedback.
yeah, I'm afraid there is no better solution. You can:
!
. I think Alex from trpc says this is one of the cases where he uses itThis 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 aMissing queryFn
error.