reactjsleafletreact-leafletesri-leaflet-geocoderreact-leaflet-search

How to resolve "React Hook useEffect has a missing dependency: 'currentPosition'"


When I include currentPosition in the useEffect dependency array or when I delete it, the code turns into an infinite loop. Why? I have the same problem with map but when I place map in the dependency array it's ok.

import { useState, useEffect } from "react";

import { useMap } from "react-leaflet";
import L from "leaflet";

import icon from "./../constants/userIcon";

const UserMarker = () => {
  const map = useMap();
  const [currentPosition, setCurrentPosition] = useState([
    48.856614,
    2.3522219,
  ]);

  useEffect(() => {
    if (navigator.geolocation) {
      let latlng = currentPosition;
      const marker = L.marker(latlng, { icon })
        .addTo(map)
        .bindPopup("Vous êtes ici.");
      map.panTo(latlng);

      navigator.geolocation.getCurrentPosition(function (position) {
        const pos = [position.coords.latitude, position.coords.longitude];
        setCurrentPosition(pos);
        marker.setLatLng(pos);
        map.panTo(pos);
      });
    } else {
      alert("Problème lors de la géolocalisation.");
    }
  }, [map]);

  return null;
};

export default UserMarker;

Solution

  • Thank you, i have resolved the conflict how this:

    import { useEffect } from "react";
    
    import { useMap } from "react-leaflet";
    import L from "leaflet";
    
    import icon from "./../constants/userIcon";
    
    const UserMarker = () => {
      const map = useMap();
    
      useEffect(() => {
        const marker = L.marker;
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function (position) {
            const latlng = [position.coords.latitude, position.coords.longitude];
            marker(latlng, { icon })
              .setLatLng(latlng)
              .addTo(map)
              .bindPopup("Vous êtes ici.");
            map.panTo(latlng);
          });
        } else {
          alert("Problème lors de la géolocalisation.");
        }
      }, [map]);
    
      return null;
    };
    
    export default UserMarker;