Explorar o código

ClickMarkerMap broken into proper custom hooks

Kirk Trombley %!s(int64=5) %!d(string=hai) anos
pai
achega
81148dd480

+ 27 - 18
client/src/components/screens/GamePanel/ClickMarkerMap.jsx

@@ -1,35 +1,44 @@
 import React, { useRef, useEffect } from "react";
 /* global google */
 
-export default ({ onMarkerMoved }) => {
-  const mapDivRef = useRef(null);
-  const mapRef = useRef(null);
-  const markerRef = useRef(null);
-
+const useMap = () => {
+  const mapDiv = useRef(null);
+  const map = useRef(null);
   useEffect(() => {
-    if (mapRef.current) {
+    if (map.current) {
       console.log("Attempted to re-run effect with existing Map");
       return;
     }
     
-    mapRef.current = new google.maps.Map(mapDivRef.current, {
+    map.current = new google.maps.Map(mapDiv.current, {
       center: { lat: 25, lng: -25 },
       zoom: 0,
       disableDefaultUI: true,
       fullscreenControl: true,
     });
+  }, []);
 
-    if (onMarkerMoved) {
-      mapRef.current.addListener("click", ({ latLng }) => {
-        if (markerRef.current) {
-          markerRef.current.setMap(null);
-        }
-        markerRef.current = new google.maps.Marker({ map: mapRef.current, position: latLng });
-        console.log({ lat: latLng.lat(), lng: latLng.lng() });
-        onMarkerMoved({ lat: latLng.lat(), lng: latLng.lng() });
-      });
-    }
-  }, [onMarkerMoved]);
+  return [mapDiv, map];
+}
+
+const useClickMarker = (map, onMove) => {
+  const marker = useRef(null);
+  useEffect(() => {
+    const listener = map.current.addListener("click", ({ latLng }) => {
+      if (marker.current) {
+        marker.current.setMap(null);
+      }
+      marker.current = new google.maps.Marker({ map: map.current, position: latLng });
+      console.log({ lat: latLng.lat(), lng: latLng.lng() });
+      onMove({ lat: latLng.lat(), lng: latLng.lng() });
+    });
 
+    return () => { google.maps.event.removeListener(listener); }
+  }, [map, onMove]);
+}
+
+export default ({ onMarkerMoved }) => {
+  const [mapDivRef, mapRef] = useMap();
+  useClickMarker(mapRef, onMarkerMoved);
   return <div className="map-div" ref={mapDivRef} />
 }

+ 1 - 1
client/src/components/util/ApiInfo.jsx

@@ -3,7 +3,7 @@ import { getStatus } from "../../domain/GGSHService";
 
 export default () => {
   const [data, setData] = useState(null);
-  useEffect(() => getStatus().then(setData), []);
+  useEffect(() => { getStatus().then(setData) }, []);
 
   if (data === null) {
     return <p>Connecting to back-end...</p>