All files / src/hooks useAddToProject.tsx

93.75% Statements 15/16
100% Branches 1/1
100% Functions 5/5
93.75% Lines 15/16

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 486x 6x 6x 6x     2x     187x 187x 187x   3x                     3x 1x             2x     2x     1x             187x    
import { useMutation } from '@tanstack/react-query';
import { request } from '@procore/core-http';
import toast from 'react-hot-toast/headless';
import { useI18nContext } from '@procore/core-react';
 
export function getRedirectUrl(vendorId: string, projectId?: string) {
  return `${window.location.origin}/${projectId}/project/directory/vendors/${vendorId}/edit?create_vendor_success=true`;
}
 
export function useAddToProject(companyId: number, projectId: string) {
  const i18n = useI18nContext();
  const mutation = useMutation({
    mutationFn: async (vendorId: number) => {
      const response = await request(
        `/rest/v1.1/projects/${projectId}/vendors/${vendorId}/actions/add`,
        {
          method: 'post',
          headers: {
            'Procore-Company-ID': companyId.toString(),
            'Content-Type': 'application/json',
          },
        }
      );
 
      if (response.status !== 201) {
        throw new Error(
          i18n.t(
            'views.generic.directory.add_company_package.hook_errors.create_vendor_failed'
          )
        );
      }
 
      return response.json();
    },
    onSuccess(data: { id: string }) {
      window.location.href = getRedirectUrl(data.id, projectId);
    },
    onError() {
      toast(
        i18n.t(
          'views.generic.directory.add_company_package.hook_errors.create_vendor_failed_toast'
        )
      );
    },
  });
  return mutation;
}