All files / src/hooks usePCNSearchQuery.tsx

100% Statements 19/19
100% Branches 2/2
100% Functions 3/3
100% Lines 19/19

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 533x 3x   3x 3x 3x     2x       2x 2x   2x     4x 4x 4x 4x 4x     2x                     2x 1x             1x           4x    
import { request } from '@procore/core-http';
import { useQuery } from '@tanstack/react-query';
import { PCNSearchResponse } from '../models/PCNSearchResponse';
import { useI18nContext } from '@procore/core-react';
import { useAddCompanyContext } from '../Context/AddCompanyContext';
import { useSearchContext } from '../Context/SearchContext';
 
function generateParams(query: string, projectId?: string) {
  const params = new URLSearchParams({
    query: query.trim().substring(0, 255),
    per_page: '5',
  });
  if (projectId) {
    params.append('project_id', projectId);
  }
  return params.toString();
}
 
export function usePCNSearchQuery() {
  const i18n = useI18nContext();
  const { companyId, projectId } = useAddCompanyContext();
  const [searchTerm] = useSearchContext();
  const query = useQuery<PCNSearchResponse>({
    queryKey: ['pcnSearch', searchTerm, companyId, projectId],
    queryFn: async () => {
      const response = await request(
        `/rest/v1.0/company/${companyId}/search/connectable_businesses?${generateParams(
          searchTerm,
          projectId
        )}`,
        {
          headers: {
            'Procore-Company-ID': companyId.toString(),
          },
        }
      );
      if (response.status >= 400) {
        throw new Error(
          i18n.t(
            'views.generic.directory.add_company_package.hook_errors.search_failed'
          )
        );
      }
 
      return response.json();
    },
    enabled: !!searchTerm,
    retry: false,
    refetchOnMount: false,
  });
  return query;
}