All files / src/hooks useGeocodingCore.tsx

100% Statements 10/10
100% Branches 0/0
100% Functions 4/4
100% Lines 9/9

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 3817x 6x                                           5x 2x     5x 5x 5x 5x         5x    
import { useEffect, useMemo } from 'react';
import { GeocodingCore, GeocodingOptions } from '@mapbox/search-js-core';
 
/**
 * A React hook that returns a {@link GeocodingCore} instance.
 *
 * @param {GeocodingOptions} options
 * @param {string} options.accessToken Your Mapbox access token.
 * @see {@link GeocodingCore}
 * @example
 * ```typescript
 * import { useGeocodingCore } from '@mapbox/search-js-react';
 * const geocodingCore = useGeocodingCore({ accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN' });
 * const response = await geocodingCore.forward('1600 pennsylvania ave nw', {
 *   limit: 1
 * });
 * console.log(response);
 * // { type: 'FeatureCollection', features: [...], attribution: '...', url: '...' };
 * ```
 */
export function useGeocodingCore(
  options: Partial<{ accessToken: string } & GeocodingOptions>
): GeocodingCore {
  const search = useMemo(() => {
    return new GeocodingCore();
  }, []);
 
  useEffect(() => {
    const { accessToken, ...restOptions } = options;
    search.accessToken = accessToken;
    search.defaults = {
      ...restOptions
    };
  }, [options]);
 
  return search;
}