Skip to content

Commit

Permalink
fix: markers not removed in strict mode (#15)
Browse files Browse the repository at this point in the history
In strict mode, the effect-hook that creates the marker is run twice in quick succession, so we can't rely on the state to refer to the marker.

fixes #14
  • Loading branch information
usefulthink authored Oct 5, 2023
1 parent 5f64f41 commit 6c4244a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 16 deletions.
11 changes: 5 additions & 6 deletions src/components/advanced-marker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,24 +70,23 @@ function useAdvancedMarker(props: AdvancedMarkerProps) {
useEffect(() => {
if (!map || !markersLibraryReady) return;

const marker = new google.maps.marker.AdvancedMarkerElement();
marker.map = map;
const newMarker = new google.maps.marker.AdvancedMarkerElement();
newMarker.map = map;

setMarker(marker);
setMarker(newMarker);

// create container for marker content if there are children
if (numChilds > 0) {
const el = document.createElement('div');
if (className) el.classList.add(className);

marker.content = el;
newMarker.content = el;

setContentContainer(el);
}

return () => {
if (marker) marker.map = null;

newMarker.map = null;
setMarker(null);
setContentContainer(null);
};
Expand Down
15 changes: 5 additions & 10 deletions src/components/marker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,18 @@ function useMarker(props: MarkerProps) {
// create marker instance and add to the map once the map is available
useEffect(() => {
if (!map) {
if (map === undefined) {
if (map === undefined)
console.error('<Marker> has to be inside a Map component.');
}

return;
}

const m = new google.maps.Marker(markerOptions);
m.setMap(map);
setMarker(m);
const newMarker = new google.maps.Marker(markerOptions);
newMarker.setMap(map);
setMarker(newMarker);

// remove from map on unmount
return () => {
if (marker) {
marker.setMap(null);
}

newMarker.setMap(null);
setMarker(null);
};
}, [map]);
Expand Down

0 comments on commit 6c4244a

Please sign in to comment.