Home > Blockchain >  Functional component event is still active when state is toggled - REACT MAPBOX
Functional component event is still active when state is toggled - REACT MAPBOX

Time:05-21

I'm trying to build an app where you can toggle effects by clicking on the navitems.

On the nav items I have an event listener that toggles state

const [marker, setMarker] = useState(false);

onClick={() => setMarker(!marker)}

The idea is when it's set to true, you can click on the map to set a waypoint. And when it's false, clicking does the default behavior.

I tried using an if statement like this

    if (marker) {
      map.current.on('click', (e) => {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
      });
    }

Whether state is true or false, you can still place a waypoint after toggling it for the first time.

Can someone please tell me what I'm missing here? I know it's something stupid.

CodePudding user response:

I've faced the same problem when I began to use React Hooks! Don't worry, that's because you have no code for removing the added click event for map Ref! So you just need to cleanup the click event for the map object!

useEffect(() => {
    function clickHandler(e) {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
    }
    if (marker) {
        map.current.on('click', (e) => {
            clickHandler(e)
        });
    }
    return () => {
        map.current.removeEventListener('click', clickHandler)
    }
}, [marker]);

Please try this way.. Good luck..

  • Related