Fix: Sicherstellen, dass MapComponent innerhalb des RecoilRoot-Kontexts liegt

- Entfernt redundanten `RecoilRoot` aus `MapComponent`, um Probleme mit verschachtelten Wurzeln zu vermeiden.
- Sichergestellt, dass `MapComponent` immer innerhalb des zentralen `RecoilRoot` gerendert wird, der in `_app.js` definiert ist.
- Das Problem "Diese Komponente muss innerhalb einer `<RecoilRoot>`-Komponente verwendet werden" durch Platzieren aller Recoil-States im korrekten Kontext behoben.
- `ShowAddStationPopup` direkt als JSX-Element innerhalb von `MapComponent` zur besseren Übersicht verwendet.
This commit is contained in:
ISA
2024-05-05 13:14:09 +02:00
parent 0448d1bc56
commit ce8d1f5a19
8 changed files with 193 additions and 223 deletions

View File

@@ -1,6 +1,6 @@
// components/MapComponent.js
import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom/client"; // Import from 'react-dom/client'
//import ReactDOM from "react-dom/client"; // Import from 'react-dom/client'
import L, { marker } from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-contextmenu/dist/leaflet.contextmenu.css";
@@ -10,7 +10,7 @@ import dynamic from "next/dynamic";
import "leaflet.smooth_marker_bouncing";
import OverlappingMarkerSpiderfier from "overlapping-marker-spiderfier-leaflet";
import DataSheet from "./DataSheet.js";
import { useRecoilState, useRecoilValue, RecoilRoot } from "recoil";
import { useRecoilState, useRecoilValue } from "recoil";
import { gisStationsStaticDistrictState } from "../store/atoms/gisStationState.js";
import { gisSystemStaticState } from "../store/atoms/gisSystemState.js";
import { mapLayersState } from "../store/atoms/mapLayersState.js";
@@ -18,9 +18,23 @@ import { selectedAreaState } from "../store/atoms/selectedAreaState.js";
import { zoomTriggerState } from "../store/atoms/zoomTriggerState.js";
import { poiTypState } from "../store/atoms/poiTypState.js";
import ShowAddStationPopup from "./ShowAddStationPopup";
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom';
//import { createRoot } from "react-dom/client";
const MapComponent = ({ locations, onLocationUpdate }) => {
const [showPopup, setShowPopup] = useState(false);
const openPopup = () => setShowPopup(true);
const closePopup = () => setShowPopup(false);
const handleAddStation = (stationData) => {
// Station-Daten speichern oder API-Aufruf durchführen
console.log("Neue Station:", stationData);
closePopup(); // Schließt das Popup nach dem Hinzufügen
};
const poiReadTrigger = useRecoilValue(poiReadFromDbTriggerAtom);
const [poiTypData, setPoiTypData] = useState(poiTypState); // Recoil State verwenden
const poiLayerRef = useRef(null); // Referenz auf die Layer-Gruppe für Datenbank-Marker
const mapRef = useRef(null); // Referenz auf das DIV-Element der Karte
@@ -257,7 +271,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
zoomControl: false,
contextmenu: true,
contextmenuItems: [
{ text: "Station hinzufügen", callback: showAddStationPopup },
{ text: "Station hinzufügen"},
{
text: "Station öffnen (Tab)",
icon: "img/screen_new.png",
@@ -307,7 +321,8 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
// Rufe hier Funktionen auf, die eine initialisierte Karte benötigen.
});
}
}, [mapRef, map]); // Prüfe die Abhängigkeiten sorgfältig
console.log("trigger in MapComponent.js:", poiReadTrigger);
}, [mapRef, map, poiReadTrigger]); // Prüfe die Abhängigkeiten sorgfältig
//------------------------------------------
function parsePoint(pointString) {
@@ -339,7 +354,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
console.error("Fehler beim Abrufen der poiTyp Daten:", error);
}
};
console.log("trigger in MapComponent.js in fetchPoiTypData:", poiReadTrigger);
fetchPoiTypData();
}, []);
@@ -409,16 +424,16 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
};
//-----Kontextmenu----ende------------
// Ensure this function is only called when map is initialized and available
const showAddStationPopup = (e, map) => {
const container = L.DomUtil.create("div");
/* const showAddStationPopup = (e, map) => {
const container = L.DomUtil.create("div");
// Create a root container for the React component inside the popup
const root = ReactDOM.createRoot(container);
root.render(
<RecoilRoot>
<ShowAddStationPopup map={initMap} latlng={e.latlng} />
</RecoilRoot>
);
// Create and configure the popup
@@ -428,22 +443,22 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
initMap.on("popupclose", () => {
root.unmount(); // Use unmount method from the root
});
};
}; */
// Inside your ShowAddStationPopup component
useEffect(() => {
/* useEffect(() => {
// Cleanup function to unmount React component
return () => {
if (container._reactRoot) {
container._reactRoot.unmount();
}
};
}, []);
}, []); */
//------------------------------------------
// Hinzufügen eines neuen Standorts (Marker) in MySQL-DB-Tabelle (poi)
async function handleSubmit(event) {
/* async function handleSubmit(event) {
event.preventDefault();
const form = event.target;
@@ -478,7 +493,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
console.error("Fehler beim Hinzufügen der Station");
// Fehlerbehandlung
}
}
} */
//---------------------------------------
@@ -547,17 +562,25 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
if (map && poiLayerRef.current) {
// Entfernen der dbLayer bei Unmount
map.removeLayer(poiLayerRef.current);
poiLayerRef.current = null;
poiLayerRef.current = new L.LayerGroup().addTo(map);
}
locations.forEach((location) => {
// Fügen Sie hier die Logik hinzu, um Marker zu erstellen und zu konfigurieren
});
};
}, [map]); // Dieser Effekt läuft nur, wenn sich `map` ändert
console.log("trigger in MapComponent.js:", poiReadTrigger);
}, [map,locations, poiReadTrigger]); // Dieser Effekt läuft nur, wenn sich `map` ändert
//------------------------------------------
// poiLayerRef
//--------------------------------------------
useEffect(() => {
if (map && poiLayerRef.current) {
// Sicherstellen, dass die alte dbLayer entfernt wird
// Entfernen Sie die bestehende Ebene und erstellen Sie eine neue
map.removeLayer(poiLayerRef.current);
poiLayerRef.current = new L.LayerGroup().addTo(map);
// Fügen Sie die aktualisierten Marker hinzu
locations.forEach((location) => {
const { latitude, longitude } = parsePoint(location.position);
const marker = L.marker([latitude, longitude], {
@@ -570,34 +593,39 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
draggable: true,
id: location.idPoi,
});
// Popup binden, aber nicht automatisch öffnen
// Popup konfigurieren
marker.bindPopup(
//N/A oder location.idPoiTyp=0 hier soll der Name von poiTyp Tabelle kommen, also foreign key
`<b>${location.description || "Unbekannt"}</b><br>Type: ${location.idPoiTyp || "N/A oder location.idPoiTyp=0"}<br>Lat: ${latitude.toFixed(5)}, Lng: ${longitude.toFixed(5)}`
`<b>${location.description || "Unbekannt"}</b><br>Type: ${
location.idPoiTyp || "N/A"
}<br>Lat: ${latitude.toFixed(5)}, Lng: ${longitude.toFixed(5)}`
);
// Event-Handler für Mouseover und Mouseout hinzufügen
// Event-Handler hinzufügen
marker.on("mouseover", function () {
this.openPopup();
});
marker.on("mouseout", function () {
this.closePopup();
});
marker.on("dragend", function (e) {
marker.on("dragend", (e) => {
const newLat = e.target.getLatLng().lat;
const newLng = e.target.getLatLng().lng;
const markerId = e.target.options.id;
updateLocationInDatabase(markerId, newLat, newLng).then(() => {
onLocationUpdate(markerId, newLat, newLng);
console.log("trigger in MapComponent.js:", poiReadTrigger);
});
});
marker.addTo(poiLayerRef.current);
});
}
}, [map, locations, onLocationUpdate]); // Dieser Effekt läuft, wenn `map`, `locations` oder `onLocationUpdate` sich ändern
}, [map, locations, onLocationUpdate,poiReadTrigger]);
//------------------------------------------
function parsePoint(position) {
const [longitude, latitude] = position.slice(6, -1).split(" ");
@@ -1476,10 +1504,30 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
}
}, [map, zoomTrigger]);
//---------------------------------------------------------
useEffect(() => {
console.log("Aktualisierung in MapComponent.js:", poiReadTrigger);
// Logik zur Aktualisierung der Map hier hinzufügen
// Beispiel: Daten neu laden oder aktualisieren
}, [poiReadTrigger]);
//---------------------------------------------------------
return (
<>
<div>
<button onClick={openPopup}>Neue Station hinzufügen</button>
{/* Direkt als JSX verwenden */}
{showPopup && (
<ShowAddStationPopup
onClose={closePopup}
onSubmit={handleAddStation}
latlng={{ lat: 52.5200, lng: 13.4050 }} // Beispielkoordinaten
/>
)}
</div>
<DataSheet className="z-50" />
<div

View File

@@ -1,16 +1,33 @@
// components/ShowAddStationPopup.js
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, use } from "react";
import ReactDOM from "react-dom";
import { useRecoilValue } from "recoil";
import { useRecoilValue ,useRecoilState, useSetRecoilState } from "recoil";
import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore";
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom';
const ShowAddStationPopup = ({ map, latlng }) => {
const loadData = useRecoilValue(readPoiMarkersStore);
const [poiTypData2, setPoiTypData2] = useState(); // Recoil State verwenden
const [name, setName] = useState("");
const [poiTypeId, setPoiTypeId] = useState(""); // Initialize as string
const [latitude] = useState(latlng.lat.toFixed(5));
const [longitude] = useState(latlng.lng.toFixed(5));
const setLoadData = useSetRecoilState(readPoiMarkersStore);
const setTrigger = useSetRecoilState(poiReadFromDbTriggerAtom);
/* useEffect(() => {
if (map && loadData) {
console.log("Map and loadData are defined in ShowAddStationPopup.js", map);
console.log("loadData object in ShowAddStationPopup.js:", loadData);
// Your code here
}else{
console.log("Map and loadData are not defined in ShowAddStationPopup.js");
}
}, [map, loadData]); */
// In Kontextmenü-Formular Typen anzeigen
useEffect(() => {
const fetchPoiTypData2 = async () => {
try {
@@ -32,32 +49,40 @@ const ShowAddStationPopup = ({ map, latlng }) => {
fetchPoiTypData2();
}, []);
const handleSubmit = async (event) => {
event.preventDefault();
const formData = {
name, // Name der Station
poiTypeId, // Typ der Station, logged as idPoiTyp
latitude, // Breitengrad
longitude, // Längengrad
};
//-----------------handleSubmit-------------------
const handleSubmit = async (event) => {
event.preventDefault();
const formData = {
name,
poiTypeId,
latitude,
longitude,
};
fetch("/api/addLocation", {
const response = await fetch("/api/addLocation", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
})
.then((response) => response.json())
.then((data) => console.log(data)) // Handle the response data
.catch((error) => console.error(error)); // Handle any errors
await loadData();
});
// Check if map is not undefined and call closePopup
if (map && typeof map.closePopup === "function") {
if (response.ok) {
setTrigger((trigger) => {
console.log("Aktueller Trigger-Wert:", trigger); // Vorheriger Wert
const newTrigger = trigger + 1;
console.log("Neuer Trigger-Wert:", newTrigger); // Aktualisierter Wert
return newTrigger;
});
} else {
console.error("Fehler beim Hinzufügen des POI");
}
if (map && typeof map.closePopup === "function") {
map.closePopup();
} else {
console.error("Map object is undefined or closePopup is not a function");
}
};
}
};
return (
<form onSubmit={handleSubmit} className="m-0 p-2 w-full ">