All files / app/features/communities hooks.ts

83.09% Statements 59/71
52% Branches 13/25
66.66% Functions 22/33
80% Lines 48/60

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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                  14x                         14x   14x                           14x 14x 14x   243x         241x   49x         241x   241x 238x 151x     87x       87x         241x             87x 85x   37x     139x     22x 20x   6x     35x     39x 37x   12x     64x   37x 37x     14x                             14x                             23x 21x     10x 31x                       14x                 28x 26x 26x   2x   1x 1x             668x                       666x   118x 539x         14x                
import {
  InfiniteData,
  keepPreviousData,
  useInfiniteQuery,
  UseInfiniteQueryOptions,
  useMutation,
  useQuery,
  useQueryClient,
  UseQueryOptions,
} from "@tanstack/react-query";
import {
  communityAdminsKey,
  communityDiscussionsKey,
  communityEventsKey,
  communityKey,
  communityMembersKey,
  communityNearbyUsersKey,
  QueryType,
  subCommunitiesKey,
  threadKey,
  userCommunitiesListKey,
  volunteersKey,
} from "features/queryKeys";
import { RpcError } from "grpc-web";
import { useRouter } from "next/router";
import {
  Community,
  ListAdminsRes,
  ListCommunitiesRes,
  ListDiscussionsRes,
  ListEventsRes,
  ListMembersRes,
  ListNearbyUsersRes,
  ListUserCommunitiesRes,
} from "proto/communities_pb";
import { Discussion } from "proto/discussions_pb";
import { GetVolunteersRes } from "proto/public_pb";
import { GetThreadRes } from "proto/threads_pb";
import { useEffect } from "react";
import { routeToCommunity } from "routes";
import { service } from "service";
 
export const useCommunity = (
  id: number,
  communitySlug?: string,
  options?: Omit<UseQueryOptions<Community.AsObject, RpcError>, "queryKey" | "queryFn" | "enabled">,
) => {
  const queryResult = useQuery({
    queryKey: communityKey(id),
    queryFn: () => (id ? service.communities.getCommunity(id) : Promise.reject(new Error("Invalid community id"))),
    ...options,
    enabled: !!id,
  });
 
  const router = useRouter();
 
  useEffect(() => {
    if (!queryResult.isSuccess) {
      return;
    }
 
    const { slug, communityId } = queryResult.data;
 
    // guarantee the most recent slug is used if the community was loaded from url params
    // if no slug was provided in the url, then also redirect to page with slug in url
    Iif (!id && slug !== communitySlug && typeof window !== "undefined") {
      router.push(routeToCommunity(communityId, slug));
    }
  }, [queryResult, router, id, communitySlug]);
 
  return {
    ...queryResult,
    id,
  };
};
 
//0 for communityId lists all communities
export const useListSubCommunities = (communityId: number) =>
  useInfiniteQuery<ListCommunitiesRes.AsObject, RpcError>({
    queryKey: subCommunitiesKey(communityId),
    queryFn: ({ pageParam }) => service.communities.listCommunities(communityId, pageParam as string | undefined),
    initialPageParam: undefined,
    enabled: communityId !== undefined,
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
  });
 
export const useListDiscussions = (communityId: number) =>
  useInfiniteQuery<ListDiscussionsRes.AsObject, RpcError>({
    queryKey: communityDiscussionsKey(communityId),
    queryFn: ({ pageParam }) => service.communities.listDiscussions(communityId, pageParam as string | undefined),
    initialPageParam: undefined,
    enabled: !!communityId,
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
  });
 
export const useListAdmins = (communityId: number, type: QueryType) => {
  const query = useInfiniteQuery<ListAdminsRes.AsObject, RpcError>({
    queryKey: communityAdminsKey(communityId, type),
    queryFn: ({ pageParam }) => service.communities.listAdmins(communityId, pageParam as string | undefined),
    initialPageParam: undefined,
    enabled: !!communityId,
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
  });
  const adminIds = query.data?.pages.flatMap((page) => page.adminUserIdsList);
  return { ...query, adminIds };
};
 
export const useListMembers = ({ communityId, pageSize }: { communityId: number; pageSize: number }) =>
  useInfiniteQuery<ListMembersRes.AsObject, RpcError>({
    queryKey: [...communityMembersKey(communityId!), pageSize],
    queryFn: ({ pageParam }) =>
      service.communities.listMembers({
        communityId: communityId,
        pageSize,
        pageToken: pageParam as string | undefined,
      }),
    initialPageParam: undefined,
    placeholderData: keepPreviousData,
    enabled: !!communityId,
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
  });
 
export const useListNearbyUsers = (communityId: number) =>
  useInfiniteQuery<ListNearbyUsersRes.AsObject, RpcError>({
    queryKey: communityNearbyUsersKey(communityId),
    queryFn: ({ pageParam }) => service.communities.listNearbyUsers(communityId, pageParam as string | undefined),
    initialPageParam: undefined,
    enabled: !!communityId,
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
  });
 
interface UseListCommunityEventsInput {
  communityId: number;
  pageSize?: number;
  type: QueryType;
}
 
export function useListCommunityEvents({ communityId, pageSize, type }: UseListCommunityEventsInput) {
  return useInfiniteQuery<ListEventsRes.AsObject, RpcError>({
    queryKey: communityEventsKey(communityId, type),
    queryFn: ({ pageParam }) =>
      service.events.listCommunityEvents(communityId, pageParam as string | undefined, pageSize),
    getNextPageParam: (lastPage) => lastPage.nextPageToken || undefined,
    initialPageParam: undefined,
  });
}
 
// Discussions
export interface CreateDiscussionInput {
  title: string;
  content: string;
  ownerCommunityId: number;
}
 
export const useListUserCommunities = () =>
  useInfiniteQuery<ListUserCommunitiesRes.AsObject, RpcError>({
    queryKey: [userCommunitiesListKey],
    queryFn: ({ pageParam }) => service.communities.listUserCommunities(pageParam as string | undefined),
    initialPageParam: undefined,
    getNextPageParam: (lastPage) => (lastPage.nextPageToken ? lastPage.nextPageToken : undefined),
    staleTime: 10 * 60 * 1000,
  });
 
export const useNewDiscussionMutation = (onSuccess?: () => void) => {
  const queryClient = useQueryClient();
  return useMutation<Discussion.AsObject, RpcError, CreateDiscussionInput>({
    mutationFn: ({ title, content, ownerCommunityId }) =>
      service.discussions.createDiscussion(title, content, ownerCommunityId),
    onSuccess(_, { ownerCommunityId }) {
      onSuccess?.();
      queryClient.invalidateQueries({
        queryKey: communityDiscussionsKey(ownerCommunityId),
      });
    },
  });
};
 
export const useThread = (
  threadId: number,
  options?: Omit<
    UseInfiniteQueryOptions<
      GetThreadRes.AsObject,
      RpcError,
      InfiniteData<GetThreadRes.AsObject>,
      ReturnType<typeof threadKey>
    >,
    "queryKey" | "queryFn" | "getNextPageParam" | "initialPageParam" | "enabled"
  > & { enabled?: boolean; initialPageParam?: string },
) =>
  useInfiniteQuery<GetThreadRes.AsObject, RpcError, InfiniteData<GetThreadRes.AsObject>, ReturnType<typeof threadKey>>({
    queryKey: threadKey(threadId),
    queryFn: ({ pageParam }) => service.threads.getThread(threadId, pageParam as string | undefined),
    getNextPageParam: (lastPage) => lastPage.nextPageToken || undefined,
    initialPageParam: undefined,
    ...options,
  });
 
export const useListVolunteers = (
  options?: Omit<UseQueryOptions<GetVolunteersRes.AsObject, RpcError>, "queryKey" | "queryFn" | "getNextPageParam">,
) =>
  useQuery<GetVolunteersRes.AsObject, RpcError>({
    queryKey: [volunteersKey],
    queryFn: () => service.publicApi.getVolunteers(),
    ...options,
  });