All files / app/features/communities/CommunityPage JoinCommunityButton.tsx

100% Statements 23/23
82.35% Branches 14/17
100% Functions 8/8
100% Lines 23/23

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 748x 8x 8x   8x 8x   8x 8x   8x         49x 49x 49x 2x     1x     1x             1x       49x 1x     1x     1x             1x       49x 49x         3x                            
import Button from "components/Button";
import Snackbar from "components/Snackbar";
import { communityKey } from "features/queryKeys";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { COMMUNITIES } from "i18n/namespaces";
import { Community } from "proto/communities_pb";
import { useMutation, useQueryClient } from "react-query";
import { service } from "service";
 
export default function JoinCommunityButton({
  community,
}: {
  community: Community.AsObject;
}) {
  const { t } = useTranslation([COMMUNITIES]);
  const queryClient = useQueryClient();
  const join = useMutation<void, RpcError>(
    () => service.communities.joinCommunity(community.communityId),
    {
      onSuccess() {
        queryClient.setQueryData<Community.AsObject | undefined>(
          communityKey(community.communityId),
          (prevData) =>
            prevData
              ? {
                  ...prevData,
                  member: true,
                }
              : undefined
        );
        queryClient.invalidateQueries(communityKey(community.communityId));
      },
    }
  );
  const leave = useMutation<void, RpcError>(
    () => service.communities.leaveCommunity(community.communityId),
    {
      onSuccess() {
        queryClient.setQueryData<Community.AsObject | undefined>(
          communityKey(community.communityId),
          (prevData) =>
            prevData
              ? {
                  ...prevData,
                  member: false,
                }
              : undefined
        );
        queryClient.invalidateQueries(communityKey(community.communityId));
      },
    }
  );
  const isLoading = join.isLoading || leave.isLoading;
  return (
    <>
      <Button
        loading={isLoading}
        variant={community.member ? "outlined" : "contained"}
        onClick={() => (community.member ? leave.mutate() : join.mutate())}
      >
        {community.member
          ? t("communities:leave_community")
          : t("communities:join_community")}
      </Button>
      {(join.isError || leave.isError) && (
        <Snackbar severity="error">
          {join.error?.message || leave.error?.message}
        </Snackbar>
      )}
    </>
  );
}