All files / app/features/userQueries useLiteUsers.ts

100% Statements 27/27
90% Branches 9/10
100% Functions 10/10
100% Lines 22/22

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 6423x 23x 23x 23x   23x   23x         988x   604x 604x   162x         604x   604x   589x   604x               84x 90x   84x                 1051x   130x         4x       1051x     1051x  
import { useQuery } from "@tanstack/react-query";
import { reactQueryRetries } from "appConstants";
import { liteUserKey, liteUsersKey } from "features/queryKeys";
import { RpcError, StatusCode } from "grpc-web";
import { GetLiteUsersRes, LiteUser } from "proto/api_pb";
import { service } from "service";
 
import { userStaleTime } from "./constants";
 
// React Query typically retains the last successful data until the next successful fetch
// if ids is `[]`, then `data` is `undefined`
function useLiteUsers(ids: (number | undefined)[] | undefined) {
  const nonFalseyIds = ids?.filter((id) => id !== undefined);
  // remove duplicate IDs from this list
  const uniqueIds = Array.from(new Set(nonFalseyIds));
  const query = useQuery<GetLiteUsersRes.AsObject, RpcError>({
    queryKey: liteUsersKey(uniqueIds),
    queryFn: async () => await service.user.getLiteUsers(uniqueIds),
    staleTime: userStaleTime,
    enabled: uniqueIds.length > 0,
  });
 
  const isDataUndefined = !query.data || !query.data.responsesList;
  const usersById =
    query.isLoading || isDataUndefined
      ? undefined
      : new Map(query?.data?.responsesList.map((response) => [response?.user?.userId, response.user]));
 
  return {
    ...query,
    data: usersById,
  };
}
 
// Like above, but returns users in a list of the same size in same order
function useLiteUsersList(ids: (number | undefined)[] | undefined) {
  const liteUsersMap = useLiteUsers(ids);
  const usersList = ids?.map((id) => liteUsersMap.data?.get(id)).filter((user): user is LiteUser.AsObject => !!user); // Type guard to remove undefined
 
  return {
    ...liteUsersMap,
    usersById: liteUsersMap.data,
    data: usersList,
  };
}
 
// React Query typically retains the last successful data until the next successful fetch
function useLiteUser(id: number | undefined) {
  const query = useQuery<LiteUser.AsObject, RpcError>({
    queryKey: liteUserKey(id),
    queryFn: () => service.user.getLiteUser(id?.toString() || ""),
    staleTime: userStaleTime,
    enabled: id !== undefined,
    retry: (failureCount, error) => {
      // don't retry if the user isn't found
      return error.code !== StatusCode.NOT_FOUND && failureCount < reactQueryRetries;
    },
  });
 
  return query;
}
 
export { useLiteUser, useLiteUsers, useLiteUsersList };