I am trying to making IP Address Tracker using Next JS. I want the coordinates of the map to change every time the user click the button.
My Map.js
file:
const Maps = ({ results }) => {
console.log(results);
const [geoData, setGeoData] = useState({ lat: null, lng: null });
let lat = results.latitude;
let lng = results.longitude;
useEffect(() => {
setGeoData({ lat: lat, lng: lng });
}, []);
console.log(geoData);
return (
<MapContainer
center={[59.2322, -12.42221]}
zoom={14}
scrollWheelZoom={false}
style={{
height: "800px",
width: "100%",
position: "absolute",
zIndex: "1",
}}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{geoData.lat && geoData.lng && (
<Marker position={[geoData.lat, geoData.lng]} />
)}
</MapContainer>
);
};
I am passing the results
from a different file.
const MapsNoSSR = dynamic(() => import("./MapsNoSSR.js"), { ssr: false
});
import dynamic from "next/dynamic";
const Header () => {
....
return
<MapsNoSSR results={results} />
}
CodePudding user response:
You would want your useEffect
hook to be called again whenever results
changes, so put results
in its dependency array. An empty dependency array means React is going to run the effect only once
const Maps = ({ results }) => {
const [geoData, setGeoData] = useState({ lat: null, lng: null });
useEffect(() => {
setGeoData({ lat: results.lattitude, lng: results.longtitude });
}, [results]);
return ...;
};
Also, make sure you are using the correct component. Seems like you have the Maps
component then also the MapsNoSSR
component