From beb0aeba03135b4d996176db4f491ff4e4aaf6ee Mon Sep 17 00:00:00 2001 From: Sergey Shishkin Date: Tue, 8 Nov 2022 15:00:45 +0100 Subject: [PATCH] fix: ensure compatibility with SSR --- src/controls.tsx | 15 ++++++--------- src/marker.tsx | 7 ++++--- src/popup.tsx | 6 ++++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/controls.tsx b/src/controls.tsx index 307d413..fc2ae5d 100644 --- a/src/controls.tsx +++ b/src/controls.tsx @@ -1,26 +1,23 @@ import * as maplibre from "maplibre-gl"; -import { createSignal, JSX, onCleanup, splitProps } from "solid-js"; +import { JSX, onCleanup, splitProps } from "solid-js"; import { useMapEffect, useMap } from "./map"; export const createControl = (ctor: new (options: Options) => Control) => (props: { options?: Options; position?: maplibre.ControlPosition }): JSX.Element => { const [own, options] = splitProps(props, ["position"]); - const [control, setControl] = createSignal(); + let control: maplibre.IControl | undefined; useMapEffect((map) => { - const existing = control(); - if (!existing) { - const created = new ctor(options.options ?? ({} as Options)) as maplibre.IControl; - map.addControl(created, own.position); - setControl(created); + if (!control) { + control = new ctor(options.options ?? ({} as Options)) as maplibre.IControl; + map.addControl(control, own.position); } }); onCleanup(() => { - const c = control(); const m = useMap()?.(); - if (c && m && m.hasControl(c)) m.removeControl(c); + if (control && m && m.hasControl(control)) m.removeControl(control); }); return <>; diff --git a/src/marker.tsx b/src/marker.tsx index 43e2926..7956023 100644 --- a/src/marker.tsx +++ b/src/marker.tsx @@ -8,10 +8,11 @@ export type MarkerProps = Partial & { export function Marker(initial: MarkerProps) { const [props, options] = splitProps(initial, ["position"]); - - const marker = new maplibre.Marker(options); + let marker: maplibre.Marker | undefined; useMapEffect((map) => { + if (!marker) marker = new maplibre.Marker(options); + if (props.position) { marker.setLngLat(props.position).addTo(map); } else { @@ -19,7 +20,7 @@ export function Marker(initial: MarkerProps) { } }); - onCleanup(() => marker.remove()); + onCleanup(() => marker?.remove()); return <>; } diff --git a/src/popup.tsx b/src/popup.tsx index 8198174..9a99d9e 100644 --- a/src/popup.tsx +++ b/src/popup.tsx @@ -10,9 +10,11 @@ export type PopUpProps = Partial & { export function Popup(initial: PopUpProps) { const [props, options] = splitProps(initial, ["position", "content"]); - const popup = new maplibre.Popup(options); + let popup: maplibre.Popup | undefined; useMapEffect((map) => { + if (!popup) popup = new maplibre.Popup(options); + if (props.position && props.content) { popup.setLngLat(props.position).setHTML(props.content).addTo(map); } else { @@ -20,7 +22,7 @@ export function Popup(initial: PopUpProps) { } }); - onCleanup(() => popup.remove()); + onCleanup(() => popup?.remove()); return <>; }