All files / src/hooks/google-api useLoadGoogleScript.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

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      100x                           100x     251x 251x   251x               251x        
import { useJsApiLoader } from "@react-google-maps/api";
import { Libraries } from "@react-google-maps/api/dist/utils/make-load-script-url";
 
const GOOGLE_MAPS_API_KEY = process.env.VITE_GOOGLE_MAPS_API_KEY;
 
// Must stay a module-level constant with a stable identity AND stable contents.
// @react-google-maps/api builds the @googlemaps/js-api-loader singleton from
// these options and re-runs `new Loader(...)` whenever `libraries` changes,
// which throws "Loader must not be called again with different options" and
// crashes the whole app (reported on a hard refresh of the event builder).
//
// `marker` is always loaded so advanced markers work when the
// GOOGLE_MAPS_ADVANCED_MARKERS flag is on; when the flag is off the library is
// simply unused (GoogleMaps.tsx renders a classic Marker at render time). The
// flag must NOT gate the loaded set: it resolves asynchronously via Flagsmith,
// so deriving `libraries` from it makes the array change after the loader has
// already been constructed with the flag's default (false) value.
const libraries: Libraries = ["places", "geocoding", "marker"];
 
function useLoadGoogleScript() {
  const language = "US";
  const region = "en-US";
 
  const { isLoaded, loadError } = useJsApiLoader({
    id: "google-maps",
    region,
    language,
    libraries,
    googleMapsApiKey: GOOGLE_MAPS_API_KEY || "not_loaded",
  });
 
  return { isLoaded, loadError };
}
 
export default useLoadGoogleScript;