Reputation: 2801
What I want is to show a loading spinner only when the query is enabled, if I try to use the isLoading
flag with the query disabled, this shows me the spinner having into account that there is no data yet in the cache.
so the question is: how do I show the loading state only when the query is enabled? if the query is disabled it should not be shown.
export const useGetCustomerProfile = (customerId) => {
const request = createClient({
url: `/customers/${customerId}/trusted-profile`,
});
return useQuery({
queryKey: ['trusted-profile', customerId],
queryFn: request,
enabled: !!customerId,
});
};
// this will show the spinner by default because there is no data in the cache
// the first time, the spinner should be only shown when `someId`
// will be different than `null || undefined`
const { isLoading } = useGetCustomerProfile(someId);
PD: I’m using react-query v4
Upvotes: 4
Views: 4077
Reputation: 29056
in v4, you can use the isInitialLoading
flag for disabled queries. This is documented here:
https://tanstack.com/query/v4/docs/guides/disabling-queries#isinitialloading
update for v5
in v5, you can now use isLoading
with disabled queries, because isLoading
is the same as isInitialLoading
. the old isLoading
was renamed to isPending
Upvotes: 5
Reputation: 6631
You need to check isIdle
which will be true when enabled is false and no data is available.
e.g.
const {
isIdle,
isLoading,
isError,
data,
error
} = useGetCustomerProfile(someId);
if(isIdle) return <NoDataInterface />;
if(isLoading) return <LoadingSpinner />;
if(isError) return <ErrorInterface error={error} />
return <InterfaceWithData data={data} />;
Upvotes: 2