TanStackT
TanStack3y ago
11 replies
brilliant-lime

Check if query finished "loading" when data === undefined is expected (i.e. 404 expected sometimes)?

I'm trying to load a user's profile, given a user ID. The user might not yet have a profile.

The query can be disabled until
userId
is know (it's loaded from the phone's keychain). I want to show either a loading screen, a create profile screen, or a view profile screen. We show the loading screen until we know whether the user has a profile and then the create/view screen, depending whether the user has a profile:

const useUserProfile = (userId?: string) => {
  const api = useApi();
  return useQuery({
    queryKey: ['users', userId!],
    queryFn: async () => {
      try {
        return await api.users.getUser(userId!);
      } catch (e) {
        if (isAxiosError(e) && e.response?.status === 404) {
          return undefined;  // Expected
        }
        throw e;
      }
    },
    enabled: userId !== undefined,
  });
};


The logic for picking the screen:

  const userId = useUserIdFromKeychain();
  const {data, isPending} = useUserProfile(userId);

  if (isPending) {
    return <LoadingScreen />;
  }

  if (!profile) {
    return <CreateProfileScreen />;
  }

  return <ProfileScreen profile={data} />;


I've read https://github.com/TanStack/query/issues/3975 and I'm still confused. How do I check if the fetched finished (a cached value is fine)?

I'm using version 5.
GitHub
Describe the bug When I created useQuery with enabled: false option, isLoading variable is always true. Your minimal, reproducible example https://codesandbox.io/s/react-query-enabled-7u58d5-7u58d5...
useQuery return always isLoading with true when enabled is false · ...
Was this page helpful?