All files / app/features/userQueries useUserByUsername.ts

92.85% Statements 26/28
68.18% Branches 15/22
80% Functions 4/5
92.85% Lines 26/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 793x 3x       3x 3x   3x 3x 3x   3x             64x           12x 12x                               64x 64x 28x 10x       64x     14x         64x 64x     64x 2x     64x 64x 64x 64x   64x                
import { reactQueryRetries } from "appConstants";
import { userKey } from "features/queryKeys";
import {
  username2IdStaleTime,
  userStaleTime,
} from "features/userQueries/constants";
import { RpcError, StatusCode } from "grpc-web";
import { User } from "proto/api_pb";
import { useEffect } from "react";
import { useQuery, useQueryClient } from "react-query";
import { service } from "service";
 
export default function useUserByUsername(
  username: string,
  invalidate = false
) {
  //We look up the userId first from the username.
  //This causes a duplicate query, but it is not made stale for a long time
  //and ensures no duplication of users in the queryCache.
  const usernameQuery = useQuery<
    { username: string; userId: number },
    RpcError
  >({
    cacheTime: username2IdStaleTime,
    queryFn: async () => {
      const user = await service.user.getUser(username);
      return {
        userId: user.userId,
        username: user.username,
      };
    },
    queryKey: ["username2Id", username],
    retry: (failureCount, error) => {
      //don't retry if the user isn't found
      return (
        error.code !== StatusCode.NOT_FOUND && failureCount <= reactQueryRetries
      );
    },
    staleTime: username2IdStaleTime,
    enabled: !!username,
  });
 
  const queryClient = useQueryClient();
  useEffect(() => {
    if (invalidate && usernameQuery.data?.userId) {
      queryClient.invalidateQueries(userKey(usernameQuery.data.userId));
    }
  }, [invalidate, queryClient, usernameQuery.data?.userId]);
 
  const query = useQuery<User.AsObject, RpcError>({
    enabled: !!usernameQuery.data,
    queryFn: () =>
      service.user.getUser(usernameQuery.data?.userId.toString() || ""),
    queryKey: userKey(usernameQuery.data?.userId ?? 0),
    staleTime: userStaleTime,
  });
 
  const errors = [];
  Iif (usernameQuery.error?.message) {
    errors.push(usernameQuery.error?.message || "");
  }
  if (query.error?.message) {
    errors.push(query.error?.message || "");
  }
 
  const error = errors.join("\n");
  const isLoading = usernameQuery.isLoading || query.isLoading;
  const isFetching = usernameQuery.isFetching || query.isFetching;
  const isError = usernameQuery.isError || query.isError;
 
  return {
    data: query.data,
    error,
    isError,
    isFetching,
    isLoading,
  };
}