Skip to content

Loader not downloading the google map script post deleting window.google object on component unmount  #358

Closed
@AkashGoenka

Description

@AkashGoenka

I have used the js-api-loader to develop a location search field which would give a list of suggestions (using the autocomplete service) when the user begins to type in the search box. This functionality is something that is not going to be used often. So, we delete the script and the window.google object on component unmount. However, we notice that on revisiting the page where this search field is located, the Loader does not make a call to refetch the google map script.

Environment details

  1. Specify the API at the beginning of the title
    places

  2. OS type and version -
    All Platforms, Windows, Mac and Linux. Desktop and Mobile as well

  3. Library version and other environment information
    "@googlemaps/js-api-loader": "~1.12.1"
    "react": "~17.0.2",
    "next": "~10.1.3",

Since we use NextJS with server side rendering enabled, the window object is available only in functions that run on the client side. Code sample below

Code example

# example 
const GOOGLE_MAP_SCRIPT_ID = 'googleMapScriptCustom';
/**
   * This hook is to cleanup the google map script and the google object once this component is unmounted
   */
  useEffect(() => {
    return () => {
      const gMapScript = document.querySelector(`#${GOOGLE_MAP_SCRIPT_ID}`);
      if (gMapScript) {
        gMapScript.remove();
        delete window.google;
      }
    };
  }, []);

 /**
   * This useEffect is used to load the Google Map Javscript API
 */
  useEffect(() => {
      new Loader({
        apiKey: googleMapsApiKey,
        id: GOOGLE_MAP_SCRIPT_ID,
        version: 'weekly',
        libraries: ['places']
      }).load();
  }, [googleMapsApiKey]);

 /**
   * This callback function is called to retrieve the location search results and is triggered on the change event in the input field
   */
  const getLocations = useCallback(async queryText => {
    if (queryText && window.google) {
      const autoCompleteServiceResults = await new window.google.maps.places.AutocompleteService().getPlacePredictions(
        {
          input: queryText,
          types: ['(cities)']
        }
      );
      setPlaces(getLocationList(autoCompleteServiceResults?.predictions) ?? []);
      setShowSuggestions(true);
    }
  }, []);
  

The above is not the complete piece of code. It is just given for a rough estimation of how we are loading and deleting the google map js script on mounting and unmounting.

Please let me know if you need any more information

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions