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 // components/MapComponent.js
import React, { useEffect, useRef, useState } from "react"; 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 L, { marker } from "leaflet";
import "leaflet/dist/leaflet.css"; import "leaflet/dist/leaflet.css";
import "leaflet-contextmenu/dist/leaflet.contextmenu.css"; import "leaflet-contextmenu/dist/leaflet.contextmenu.css";
@@ -10,7 +10,7 @@ import dynamic from "next/dynamic";
import "leaflet.smooth_marker_bouncing"; import "leaflet.smooth_marker_bouncing";
import OverlappingMarkerSpiderfier from "overlapping-marker-spiderfier-leaflet"; import OverlappingMarkerSpiderfier from "overlapping-marker-spiderfier-leaflet";
import DataSheet from "./DataSheet.js"; import DataSheet from "./DataSheet.js";
import { useRecoilState, useRecoilValue, RecoilRoot } from "recoil"; import { useRecoilState, useRecoilValue } from "recoil";
import { gisStationsStaticDistrictState } from "../store/atoms/gisStationState.js"; import { gisStationsStaticDistrictState } from "../store/atoms/gisStationState.js";
import { gisSystemStaticState } from "../store/atoms/gisSystemState.js"; import { gisSystemStaticState } from "../store/atoms/gisSystemState.js";
import { mapLayersState } from "../store/atoms/mapLayersState.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 { zoomTriggerState } from "../store/atoms/zoomTriggerState.js";
import { poiTypState } from "../store/atoms/poiTypState.js"; import { poiTypState } from "../store/atoms/poiTypState.js";
import ShowAddStationPopup from "./ShowAddStationPopup"; import ShowAddStationPopup from "./ShowAddStationPopup";
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom';
//import { createRoot } from "react-dom/client"; //import { createRoot } from "react-dom/client";
const MapComponent = ({ locations, onLocationUpdate }) => { 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 [poiTypData, setPoiTypData] = useState(poiTypState); // Recoil State verwenden
const poiLayerRef = useRef(null); // Referenz auf die Layer-Gruppe für Datenbank-Marker const poiLayerRef = useRef(null); // Referenz auf die Layer-Gruppe für Datenbank-Marker
const mapRef = useRef(null); // Referenz auf das DIV-Element der Karte const mapRef = useRef(null); // Referenz auf das DIV-Element der Karte
@@ -257,7 +271,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
zoomControl: false, zoomControl: false,
contextmenu: true, contextmenu: true,
contextmenuItems: [ contextmenuItems: [
{ text: "Station hinzufügen", callback: showAddStationPopup }, { text: "Station hinzufügen"},
{ {
text: "Station öffnen (Tab)", text: "Station öffnen (Tab)",
icon: "img/screen_new.png", icon: "img/screen_new.png",
@@ -307,7 +321,8 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
// Rufe hier Funktionen auf, die eine initialisierte Karte benötigen. // 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) { function parsePoint(pointString) {
@@ -339,7 +354,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
console.error("Fehler beim Abrufen der poiTyp Daten:", error); console.error("Fehler beim Abrufen der poiTyp Daten:", error);
} }
}; };
console.log("trigger in MapComponent.js in fetchPoiTypData:", poiReadTrigger);
fetchPoiTypData(); fetchPoiTypData();
}, []); }, []);
@@ -409,16 +424,16 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
}; };
//-----Kontextmenu----ende------------ //-----Kontextmenu----ende------------
// Ensure this function is only called when map is initialized and available // Ensure this function is only called when map is initialized and available
const showAddStationPopup = (e, map) => { /* const showAddStationPopup = (e, map) => {
const container = L.DomUtil.create("div"); const container = L.DomUtil.create("div");
// Create a root container for the React component inside the popup // Create a root container for the React component inside the popup
const root = ReactDOM.createRoot(container); const root = ReactDOM.createRoot(container);
root.render( root.render(
<RecoilRoot>
<ShowAddStationPopup map={initMap} latlng={e.latlng} /> <ShowAddStationPopup map={initMap} latlng={e.latlng} />
</RecoilRoot>
); );
// Create and configure the popup // Create and configure the popup
@@ -428,22 +443,22 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
initMap.on("popupclose", () => { initMap.on("popupclose", () => {
root.unmount(); // Use unmount method from the root root.unmount(); // Use unmount method from the root
}); });
}; }; */
// Inside your ShowAddStationPopup component // Inside your ShowAddStationPopup component
useEffect(() => { /* useEffect(() => {
// Cleanup function to unmount React component // Cleanup function to unmount React component
return () => { return () => {
if (container._reactRoot) { if (container._reactRoot) {
container._reactRoot.unmount(); container._reactRoot.unmount();
} }
}; };
}, []); }, []); */
//------------------------------------------ //------------------------------------------
// Hinzufügen eines neuen Standorts (Marker) in MySQL-DB-Tabelle (poi) // Hinzufügen eines neuen Standorts (Marker) in MySQL-DB-Tabelle (poi)
async function handleSubmit(event) { /* async function handleSubmit(event) {
event.preventDefault(); event.preventDefault();
const form = event.target; const form = event.target;
@@ -478,7 +493,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
console.error("Fehler beim Hinzufügen der Station"); console.error("Fehler beim Hinzufügen der Station");
// Fehlerbehandlung // Fehlerbehandlung
} }
} } */
//--------------------------------------- //---------------------------------------
@@ -547,17 +562,25 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
if (map && poiLayerRef.current) { if (map && poiLayerRef.current) {
// Entfernen der dbLayer bei Unmount // Entfernen der dbLayer bei Unmount
map.removeLayer(poiLayerRef.current); 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(() => { useEffect(() => {
if (map && poiLayerRef.current) { 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); map.removeLayer(poiLayerRef.current);
poiLayerRef.current = new L.LayerGroup().addTo(map); poiLayerRef.current = new L.LayerGroup().addTo(map);
// Fügen Sie die aktualisierten Marker hinzu
locations.forEach((location) => { locations.forEach((location) => {
const { latitude, longitude } = parsePoint(location.position); const { latitude, longitude } = parsePoint(location.position);
const marker = L.marker([latitude, longitude], { const marker = L.marker([latitude, longitude], {
@@ -571,13 +594,14 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
id: location.idPoi, id: location.idPoi,
}); });
// Popup binden, aber nicht automatisch öffnen // Popup konfigurieren
marker.bindPopup( 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: ${
`<b>${location.description || "Unbekannt"}</b><br>Type: ${location.idPoiTyp || "N/A oder location.idPoiTyp=0"}<br>Lat: ${latitude.toFixed(5)}, Lng: ${longitude.toFixed(5)}` 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 () { marker.on("mouseover", function () {
this.openPopup(); this.openPopup();
}); });
@@ -585,19 +609,23 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
this.closePopup(); this.closePopup();
}); });
marker.on("dragend", function (e) { marker.on("dragend", (e) => {
const newLat = e.target.getLatLng().lat; const newLat = e.target.getLatLng().lat;
const newLng = e.target.getLatLng().lng; const newLng = e.target.getLatLng().lng;
const markerId = e.target.options.id; const markerId = e.target.options.id;
updateLocationInDatabase(markerId, newLat, newLng).then(() => { updateLocationInDatabase(markerId, newLat, newLng).then(() => {
onLocationUpdate(markerId, newLat, newLng); onLocationUpdate(markerId, newLat, newLng);
console.log("trigger in MapComponent.js:", poiReadTrigger);
}); });
}); });
marker.addTo(poiLayerRef.current); 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) { function parsePoint(position) {
const [longitude, latitude] = position.slice(6, -1).split(" "); const [longitude, latitude] = position.slice(6, -1).split(" ");
@@ -1476,10 +1504,30 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
} }
}, [map, zoomTrigger]); }, [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 ( 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" /> <DataSheet className="z-50" />
<div <div

View File

@@ -1,16 +1,33 @@
// components/ShowAddStationPopup.js // components/ShowAddStationPopup.js
import React, { useState, useEffect } from "react"; import React, { useState, useEffect, use } from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import { useRecoilValue } from "recoil"; import { useRecoilValue ,useRecoilState, useSetRecoilState } from "recoil";
import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore"; import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore";
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom';
const ShowAddStationPopup = ({ map, latlng }) => { const ShowAddStationPopup = ({ map, latlng }) => {
const loadData = useRecoilValue(readPoiMarkersStore);
const [poiTypData2, setPoiTypData2] = useState(); // Recoil State verwenden const [poiTypData2, setPoiTypData2] = useState(); // Recoil State verwenden
const [name, setName] = useState(""); const [name, setName] = useState("");
const [poiTypeId, setPoiTypeId] = useState(""); // Initialize as string const [poiTypeId, setPoiTypeId] = useState(""); // Initialize as string
const [latitude] = useState(latlng.lat.toFixed(5)); const [latitude] = useState(latlng.lat.toFixed(5));
const [longitude] = useState(latlng.lng.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(() => { useEffect(() => {
const fetchPoiTypData2 = async () => { const fetchPoiTypData2 = async () => {
try { try {
@@ -32,33 +49,41 @@ const ShowAddStationPopup = ({ map, latlng }) => {
fetchPoiTypData2(); fetchPoiTypData2();
}, []); }, []);
//-----------------handleSubmit-------------------
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const formData = { const formData = {
name, // Name der Station name,
poiTypeId, // Typ der Station, logged as idPoiTyp poiTypeId,
latitude, // Breitengrad latitude,
longitude, // Längengrad longitude,
}; };
fetch("/api/addLocation", { const response = await fetch("/api/addLocation", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData), body: JSON.stringify(formData),
}) });
.then((response) => response.json())
.then((data) => console.log(data)) // Handle the response data if (response.ok) {
.catch((error) => console.error(error)); // Handle any errors setTrigger((trigger) => {
await loadData(); 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");
}
// Check if map is not undefined and call closePopup
if (map && typeof map.closePopup === "function") { if (map && typeof map.closePopup === "function") {
map.closePopup(); map.closePopup();
} else {
console.error("Map object is undefined or closePopup is not a function");
} }
}; };
return ( return (
<form onSubmit={handleSubmit} className="m-0 p-2 w-full "> <form onSubmit={handleSubmit} className="m-0 p-2 w-full ">
<div className="flex items-center mb-4"> <div className="flex items-center mb-4">

View File

@@ -23,17 +23,17 @@ if (typeof window !== "undefined") {
user = url.searchParams.get("u") || "484"; // Ein weiterer Parameter aus der URL, Standardwert ist '484 admin zu testen von Stationen ausblenden und einblenden in der Card' user = url.searchParams.get("u") || "484"; // Ein weiterer Parameter aus der URL, Standardwert ist '484 admin zu testen von Stationen ausblenden und einblenden in der Card'
// Konstruktion von URLs, die auf spezifische Ressourcen auf dem Server zeigen // Konstruktion von URLs, die auf spezifische Ressourcen auf dem Server zeigen
mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${c}&idUser=${user}`; //idMap: 10, idUser: 484 /* mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${c}&idUser=${user}`; //idMap: 10, idUser: 484
mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict?idMap=${c}&idUser=${user}`; mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict?idMap=${c}&idUser=${user}`;
mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${c}`; mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${c}`;
mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${c}&idUser=${user}`; mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${c}&idUser=${user}`;
mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; */
/* mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict`; mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict`;
mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict`; mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict`;
mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements`; mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements`;
mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`; mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`;
mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; */ mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`;
} }
// Export der definierten Variablen und URLs, damit sie in anderen Teilen der Anwendung verwendet werden können // Export der definierten Variablen und URLs, damit sie in anderen Teilen der Anwendung verwendet werden können

View File

@@ -2,8 +2,8 @@
import { createProxyMiddleware } from "http-proxy-middleware"; import { createProxyMiddleware } from "http-proxy-middleware";
export default createProxyMiddleware({ export default createProxyMiddleware({
target: "http://10.10.0.13", // Ziel-URL des Proxys //target: "http://10.10.0.13", // Ziel-URL des Proxys
//target: "http://192.168.10.187:3000", // Ziel-URL des Proxys target: "http://192.168.10.187:3000", // Ziel-URL des Proxys
changeOrigin: true, changeOrigin: true,
pathRewrite: { pathRewrite: {
"^/api": "/", // Optional: Entfernt /api aus dem Pfad, wenn das Backend dies nicht erfordert "^/api": "/", // Optional: Entfernt /api aus dem Pfad, wenn das Backend dies nicht erfordert

View File

@@ -1,98 +0,0 @@
// pages/index.js
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { useSetRecoilState } from "recoil";
import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore";
const MapComponentWithNoSSR = dynamic(
() => import("../components/MapComponent"),
{ ssr: false }
);
export default function Home() {
const setLoadData = useSetRecoilState(readPoiMarkersStore);
const [mParam, setMParam] = useState([""]);
const [uParam, setUParam] = useState([""]);
const [locations, setLocations] = useState([]);
const [formData, setFormData] = useState({
name: "",
longitude: "",
latitude: "",
type: "",
});
const loadData = async () => {
const response = await fetch("/api/readLocations");
const data = await response.json();
setLocations(data);
};
useEffect(() => {
setLoadData(async () => {
const response = await fetch("/api/readLocations");
const data = await response.json();
setLocations(data); // Überlegungen für setLocations beachten
});
}, []);
useEffect(() => {
// Funktion, um URL-Parameter zu holen
function getURLParameter(name) {
// Nutze URLSearchParams, eine Web API für die Arbeit mit Query-Strings
const params = new URLSearchParams(window.location.search);
return params.get(name); // Holt den Wert des Parameternamens
}
// Hole die Parameter 'm' und 'u'
setMParam(getURLParameter("m"));
setUParam(getURLParameter("u"));
// Logge die Werte in der Konsole
console.log(`Parameter m: ${mParam}, Parameter u: ${uParam}`);
loadData();
}, []);
const handleAddLocation = async (name, type, lat, lng) => {
const response = await fetch("/api/addLocation", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
type,
latitude: lat,
longitude: lng,
}),
});
if (response.ok) {
console.log("Standort erfolgreich hinzugefügt");
setFormData({ name: "", longitude: "", latitude: "", type: "" }); // Formular zurücksetzen
loadData(); // Daten erneut laden
} else {
console.error("Fehler beim Hinzufügen des Standorts");
}
};
const handleLocationUpdate = (id, newLatitude, newLongitude) => {
setLocations((prevLocations) => {
return prevLocations.map((location) => {
if (location.idPoi === id) {
return {
...location,
// Hier musst du ggf. die Formatierung anpassen, je nachdem wie du die Koordinaten speicherst
position: `POINT(${newLongitude} ${newLatitude})`,
};
}
return location;
});
});
};
return (
<div>
{/* Ihr Formular */}
<MapComponentWithNoSSR
locations={locations}
onAddLocation={handleAddLocation}
onLocationUpdate={handleLocationUpdate}
/>
</div>
);
}

View File

@@ -1,93 +1,85 @@
// pages/index.js // pages/index.js
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import { useSetRecoilState } from "recoil"; import { useRecoilState , useRecoilValue} from "recoil";
import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore"; import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore"; // Aktualisiert mit atom
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom';
const MapComponentWithNoSSR = dynamic( const MapComponentWithNoSSR = dynamic(
() => import("../components/MapComponent"), () => import("../components/MapComponent"),
{ ssr: false } { ssr: false }
); );
export default function Home() { export default function Home() {
const setLoadData = useSetRecoilState(readPoiMarkersStore); const poiReadTrigger = useRecoilValue(poiReadFromDbTriggerAtom);
const [mParam, setMParam] = useState([""]); const [locations, setLocations] = useRecoilState(readPoiMarkersStore);
const [uParam, setUParam] = useState([""]); const [mParam, setMParam] = useState("");
const [uParam, setUParam] = useState("");
const [locations, setLocations] = useState([]);
const [formData, setFormData] = useState({
name: "",
longitude: "",
latitude: "",
type: "",
});
const loadData = async () => { const loadData = async () => {
try {
const response = await fetch("/api/readLocations"); const response = await fetch("/api/readLocations");
if (!response.ok) {
throw new Error("Fehler beim Laden der Standortdaten");
}
const data = await response.json(); const data = await response.json();
setLocations(data); setLocations(data);
}; console.log("Geladene Daten in Home.js:", data);
useEffect(() => { } catch (error) {
setLoadData(async () => { console.error(error.message);
const response = await fetch("/api/readLocations");
const data = await response.json();
setLocations(data); // Überlegungen für setLocations beachten
});
}, []);
useEffect(() => {
// Funktion, um URL-Parameter zu holen
function getURLParameter(name) {
// Nutze URLSearchParams, eine Web API für die Arbeit mit Query-Strings
const params = new URLSearchParams(window.location.search);
return params.get(name); // Holt den Wert des Parameternamens
} }
};
// Hole die Parameter 'm' und 'u' useEffect(() => {
// URL-Parameter abfragen
function getURLParameter(name) {
const params = new URLSearchParams(window.location.search);
return params.get(name);
}
setMParam(getURLParameter("m")); setMParam(getURLParameter("m"));
setUParam(getURLParameter("u")); setUParam(getURLParameter("u"));
// Logge die Werte in der Konsole // Daten beim Laden der Seite holen
console.log(`Parameter m: ${mParam}, Parameter u: ${uParam}`);
loadData(); loadData();
}, []); console.log("poiReadTrigger in Home.js:", poiReadTrigger);
}, [poiReadTrigger]);
const handleAddLocation = async (name, type, lat, lng) => { const handleAddLocation = async (name, type, lat, lng) => {
try {
const response = await fetch("/api/addLocation", { const response = await fetch("/api/addLocation", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({ name, type, latitude: lat, longitude: lng }),
name,
type,
latitude: lat,
longitude: lng,
}),
}); });
if (!response.ok) {
if (response.ok) { throw new Error("Fehler beim Hinzufügen des Standorts");
}
console.log("Standort erfolgreich hinzugefügt"); console.log("Standort erfolgreich hinzugefügt");
setFormData({ name: "", longitude: "", latitude: "", type: "" }); // Formular zurücksetzen loadData(); // Aktualisiere die Daten nach dem Hinzufügen
loadData(); // Daten erneut laden console.log("poiReadTrigger in Home.js:", poiReadTrigger);
} else { } catch (error) {
console.error("Fehler beim Hinzufügen des Standorts"); console.error(error.message);
} }
}; };
const handleLocationUpdate = (id, newLatitude, newLongitude) => { const handleLocationUpdate = (id, newLatitude, newLongitude) => {
setLocations((prevLocations) => { setLocations((prevLocations) =>
return prevLocations.map((location) => { prevLocations.map((location) =>
if (location.idPoi === id) { location.idPoi === id
return { ? { ...location, position: `POINT(${newLongitude} ${newLatitude})` }
...location, : location
// Hier musst du ggf. die Formatierung anpassen, je nachdem wie du die Koordinaten speicherst )
position: `POINT(${newLongitude} ${newLatitude})`, );
};
}
return location;
});
});
}; };
//------------------------------------
// Daten beim Laden der Seite holen
useEffect(() => {
loadData();
console.log("poiReadTrigger in Home.js:", poiReadTrigger);
}, [poiReadTrigger]);
//------------------------------------
return ( return (
<div> <div>
{/* Ihr Formular */}
<MapComponentWithNoSSR <MapComponentWithNoSSR
locations={locations} locations={locations}
onAddLocation={handleAddLocation} onAddLocation={handleAddLocation}

View File

@@ -0,0 +1,7 @@
// store/atoms/poiReadFromDbTriggerAtom.js
import { atom } from 'recoil';
export const poiReadFromDbTriggerAtom = atom({
key: 'poiReadFromDbTriggerAtom',
default: 0, // Sie können auch einen booleschen Wert verwenden
});

View File

@@ -1,11 +1,7 @@
// store/readPoiMarkersStore.js //store/selectors/readPoiMarkersStore.js
import { atom } from "recoil"; import { atom } from 'recoil';
export const readPoiMarkersStore = atom({ export const readPoiMarkersStore = atom({
key: "readPoiMarkersStore", key: 'readPoiMarkersStore',
default: async () => { default: [],
const response = await fetch("/api/readLocations");
const data = await response.json();
return data;
},
}); });