What is the reasoning for useQuery/useMutation etc to _not_ return a union of states? #5701
Unanswered
paulyokuda
asked this question in
Q&A
Replies: 1 comment 4 replies
-
I am not affiliated with the project, but I can answer this question ... the result is already a discriminated union and should already narrow the type when you use the Given this example: import { useQuery } from '@tanstack/react-query';
import { VFC } from 'react';
type WidgetData = {
id: number;
name: string;
};
const api = {
getWidgetData: (id: number): Promise<WidgetData> => Promise.resolve({ id, name: 'Widget' }),
};
const getWidgetData = (id: number) => ({
queryKey: ['getWidgetData', id],
queryFn: () => api.getWidgetData(id),
});
export type MyWidgetProps = {
id: number;
};
export const MyWidget: VFC<MyWidgetProps> = ({ id }) => {
const { data, isLoading, isError } = useQuery(getWidgetData(id));
if (isLoading) return <Loader />;
if (isError) return <ErrorPanel />;
return <MyWidgetContent widget={data} />;
};
// Examples to make compiler happy
const Loader = () => <div>Loading</div>;
const ErrorPanel = () => <div>Error</div>;
const MyWidgetContent = ({ widget }: { widget: WidgetData }) => <div>{widget.name}</div>; You can see that |
Beta Was this translation helpful? Give feedback.
4 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.
Uh oh!
There was an error while loading. Please reload this page.
-
useQuery/useMutation both return fields like
{ data, isLoading, isError } = useQuery( ... )
, which forces consumers to have ordered checks for these things e.g.One pattern I've found to be nice for these things is to have the data object be a tagged union ('loading', 'error', 'loaded') since my data can only be in one of those states at a time. Two questions:
Beta Was this translation helpful? Give feedback.
All reactions