All files / src/features/Permissions/ModalV2/hooks useChangeRole.ts

88.88% Statements 16/18
50% Branches 1/2
100% Functions 3/3
94.11% Lines 16/17

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                6x         100x 100x 100x   100x 1x     1x             100x 1x   1x 1x 1x   1x 1x   1x           100x                    
import { showMessage } from "@common/Toast";
import { QKEY_LIST_TEAM_MEMBER_PERMISSIONS } from "@constants/queryKeys";
import { useGetCurrentMerchantId } from "@hooks/common";
import { customInstance } from "@services/api";
import { MemberRoleName } from "@customTypes/team.member";
import { useState } from "react";
import { useMutation, useQueryClient } from "react-query";
 
const useChangeRole = (
  role: string,
  member_id: number,
  updateRole: (newRole: MemberRoleName) => void,
) => {
  const [title, setTitle] = useState<MemberRoleName>("member");
  const queryClient = useQueryClient();
  const { merchantId } = useGetCurrentMerchantId();
 
  const { mutateAsync } = useMutation(async (newRole: string) => {
    const updateData = {
      memberRole: newRole,
    };
    return customInstance({
      url: `/accounts/${merchantId}/members/${member_id}`,
      method: "PATCH",
      data: updateData,
    });
  });
 
  const onSubmit = async (newRole: MemberRoleName) => {
    Iif (newRole === role) return;
 
    try {
      await mutateAsync(newRole);
      updateRole(newRole);
 
      await queryClient.invalidateQueries(QKEY_LIST_TEAM_MEMBER_PERMISSIONS);
      queryClient.invalidateQueries("add-permission-modal-list");
 
      showMessage("Success", "Role Updated");
    } catch (error) {
      showMessage("Error", "An error occured");
    }
  };
 
  return { title, setTitle, onSubmit };
};
 
export default useChangeRole;
 
type TUserRole = {
  label: string;
  value: MemberRoleName;
  disabled?: boolean;
};