All files / app/features/connections/friends AddFriendButton.tsx

92.3% Statements 24/26
0% Branches 0/2
100% Functions 6/6
92.3% Lines 24/26

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 723x 3x 3x   3x 3x 3x 3x 3x 3x                 3x       10x 10x 10x       3x   3x   3x   3x       3x           3x       1x 1x           1x       10x       3x                
import Button from "components/Button";
import { PersonAddIcon } from "components/Icons";
import { userKey } from "features/queryKeys";
import { Empty } from "google-protobuf/google/protobuf/empty_pb";
import { CONNECTIONS } from "i18n/namespaces";
import { useTranslation } from "next-i18next";
import { User } from "proto/api_pb";
import React from "react";
import { useMutation, useQueryClient } from "react-query";
import { service } from "service";
 
import { SetMutationError } from ".";
 
interface AddFriendButtonProps {
  setMutationError: SetMutationError;
  userId: number;
}
 
export default function AddFriendButton({
  setMutationError,
  userId,
}: AddFriendButtonProps) {
  const queryClient = useQueryClient();
  const { t } = useTranslation([CONNECTIONS]);
  const { isLoading, mutate: sendFriendRequest } = useMutation<
    Empty,
    Error,
    AddFriendButtonProps
  >(({ userId }) => service.api.sendFriendRequest(userId), {
    onMutate: async ({ setMutationError }) => {
      setMutationError("");
 
      await queryClient.cancelQueries(userKey(userId));
 
      const cachedUser = queryClient.getQueryData<User.AsObject>(
        userKey(userId)
      );
 
      Iif (cachedUser) {
        queryClient.setQueryData<User.AsObject>(userKey(userId), {
          ...cachedUser,
          friends: User.FriendshipStatus.PENDING,
        });
      }
      return cachedUser;
    },
 
    onError: (error, { setMutationError }, cachedUser) => {
      setMutationError(error.message);
      Iif (cachedUser) {
        queryClient.setQueryData(userKey(userId), cachedUser);
      }
    },
 
    onSuccess: (_, { userId }) => {
      queryClient.invalidateQueries(userKey(userId));
    },
  });
 
  return (
    <Button
      startIcon={<PersonAddIcon />}
      onClick={() => {
        sendFriendRequest({ setMutationError, userId });
      }}
      loading={isLoading}
    >
      {t("connections:add_friend")}
    </Button>
  );
}