Skip to content

Commit

Permalink
Merge pull request #3375 from brandensilva/fix-polygons-not-tearing-down
Browse files Browse the repository at this point in the history
fix: alter state to allow polygon to tear down on unmount, setMap reference on polygon
  • Loading branch information
JustFly1984 authored Sep 7, 2024
2 parents 31fd3db + d9bbc62 commit fe63636
Showing 1 changed file with 16 additions and 29 deletions.
45 changes: 16 additions & 29 deletions packages/react-google-maps-api/src/components/drawing/Polygon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,6 @@ const updaterMap = {
},
}

interface PolygonState {
polygon: google.maps.Polygon | null
}

export interface PolygonProps {
options?: google.maps.PolygonOptions | undefined
/** If set to true, the user can drag this shape over the map. The geodesic property defines the mode of dragging. */
Expand Down Expand Up @@ -494,66 +490,57 @@ function PolygonFunctional({

export const PolygonF = memo(PolygonFunctional)

export class Polygon extends PureComponent<PolygonProps, PolygonState> {
export class Polygon extends PureComponent<PolygonProps> {
static override contextType = MapContext
declare context: ContextType<typeof MapContext>

registeredEvents: google.maps.MapsEventListener[] = []

override state: PolygonState = {
polygon: null,
}

setPolygonCallback = (): void => {
if (this.state.polygon !== null && this.props.onLoad) {
this.props.onLoad(this.state.polygon)
}
}
polygon: google.maps.Polygon | undefined

override componentDidMount(): void {
const polygon = new google.maps.Polygon({
...(this.props.options || {}),
map: this.context,
})
const polygonOptions = this.props.options || {}

this.polygon = new google.maps.Polygon(polygonOptions)

this.polygon.setMap(this.context)

this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({
updaterMap,
eventMap,
prevProps: {},
nextProps: this.props,
instance: polygon,
instance: this.polygon,
})

this.setState(function setPolygon() {
return {
polygon,
}
}, this.setPolygonCallback)
if (this.props.onLoad) {
this.props.onLoad(this.polygon)
}
}

override componentDidUpdate(prevProps: PolygonProps): void {
if (this.state.polygon !== null) {
if (this.polygon) {
unregisterEvents(this.registeredEvents)

this.registeredEvents = applyUpdatersToPropsAndRegisterEvents({
updaterMap,
eventMap,
prevProps,
nextProps: this.props,
instance: this.state.polygon,
instance: this.polygon,
})
}
}

override componentWillUnmount(): void {
if (this.state.polygon !== null) {
if (this.polygon) {
if (this.props.onUnmount) {
this.props.onUnmount(this.state.polygon)
this.props.onUnmount(this.polygon)
}

unregisterEvents(this.registeredEvents)

this.state.polygon && this.state.polygon.setMap(null)
this.polygon && this.polygon.setMap(null)
}
}

Expand Down

0 comments on commit fe63636

Please sign in to comment.