T
TanStack14mo ago
stormy-gold

query data type is (Type | undefined) after `isError` check

const getVisitById = async (id: number): Promise<VisitResponse> => {
return await GET(`/visits/${id}`);
};


const { data, isError, error } = useQuery({
queryKey: ['visit', 18657],
queryFn: () => getVisitById(18657),
});

if (isError) {
return <div>{error.message}</div>;
}

console.log(data)
const getVisitById = async (id: number): Promise<VisitResponse> => {
return await GET(`/visits/${id}`);
};


const { data, isError, error } = useQuery({
queryKey: ['visit', 18657],
queryFn: () => getVisitById(18657),
});

if (isError) {
return <div>{error.message}</div>;
}

console.log(data)
I expect data to be type of VisitResponse after isError check, but it is VisitResponse | undefined If I do the following I get the type of VisitResponse for data
if (isError) {
return <div>{error.message}</div>;
}

if (!isSuccess) return

console.log(data)
if (isError) {
return <div>{error.message}</div>;
}

if (!isSuccess) return

console.log(data)
Is there way to change this behaviour so that checking only isError would suffice?
4 Replies
wise-white
wise-white14mo ago
you haven't checked for isPending, so it's not guaranteed that data is there
stormy-gold
stormy-goldOP14mo ago
So, would the following be the correct approach?
if (isLoading || isPending) return <h1>Loading...</h1>;

if (isError) return <h1>Error</h1>;

console.log(data);
if (isLoading || isPending) return <h1>Loading...</h1>;

if (isError) return <h1>Error</h1>;

console.log(data);
wise-white
wise-white14mo ago
if (isPending) is enough
stormy-gold
stormy-goldOP14mo ago
Migrating to TanStack Query v5 | TanStack Query React Docs
Breaking Changes v5 is a major version, so there are some breaking changes to be aware of:

Did you find this page helpful?