All files / src/hooks/mutations useGeocodeMutation.ts

66.66% Statements 6/9
33.33% Branches 2/6
75% Functions 3/4
75% Lines 6/8

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                                                      3x 203x   8x   5x             5x     3x        
// src/hooks/mutations/useGeocodeMutation.ts
import { useMutation } from '@tanstack/react-query';
import { geocodeAddress } from '../../services/apiClient';
import { notifyError } from '../../services/notificationService';
 
interface GeocodeResult {
  lat: number;
  lng: number;
}
 
/**
 * Mutation hook for geocoding an address string to coordinates.
 *
 * @returns TanStack Query mutation for geocoding
 *
 * @example
 * ```tsx
 * const geocodeMutation = useGeocodeMutation();
 *
 * const handleGeocode = async () => {
 *   const result = await geocodeMutation.mutateAsync('123 Main St, City, State');
 *   if (result) {
 *     console.log(result.lat, result.lng);
 *   }
 * };
 * ```
 */
export const useGeocodeMutation = () => {
  return useMutation({
    mutationFn: async (address: string): Promise<GeocodeResult> => {
      const response = await geocodeAddress(address);
 
      Iif (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Geocoding failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to geocode address');
      }
 
      return response.json();
    },
    onError: (error: Error) => {
      notifyError(error.message || 'Failed to geocode address');
    },
  });
};