react-mapbox-gl: onClick does not see state hooks changes

I am using react 16.8 hooks, in the map component I define an onClick function, but when I retrieve the value of the state hooks me the initial value is returned.

in the visualization it is possible to see the updated value of count, but within the function it is not possible

const [count,setCount] = useState(0); ... .... ... onClick={(map, evt) => { console.log(count); // Caso o indicador criando marcador esteja ativo ira criar marcadores no mapa. const { lng, lat } = evt.lngLat; setCriandoMarcador(true); if (criandoMarcador) { setPontosGps([...pontosGps, { lng, lat }]); if (!travarFerramenta) { setCriandoMarcador(false); } } }}

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 6
  • Comments: 16 (1 by maintainers)

Most upvoted comments

Should be fixed in the latest version, thanks to the PR by @sanfilippopablo. If true, let’s close this.

I also noticed that the behavior of onClick is captured and never changed. I will rewrite @crosskpixel example to be more comprehensible:

const ReactHookComponent = () => {
    const [count, setCount] = useState(0);

    useEffect(() => {
        setCount(c => c+1); // start by increment count from 0 to 1
    }, []);

    const handleClick = () => {
        console.log('Map clicked with count', count); // will display 'Map clicked with count 0'. State is not up to date
    }

   return (
        <Map onClick={handleClick} />
    )
}

At the moment, a crappy way to work this around is to use a ref:

    const countForMap = useRef(0);

    useEffect(() => {
       countForMap.current = count;
   }, [count])

   const handleClick = () => {
        console.log('Map clicked with count', countForMap.current); // will display 'Map clicked with count 1
    }

Since, it’s still not merged, I have

// https://github.com/alex3165/react-mapbox-gl/issues/748#issuecomment-569395282
  const _WORKAROUND_showList = React.useRef(true);
  const [, forceUpdate] = React.useState();
  // const [showList, setShowList] = React.useState(true);

// and

const handleMapClick = React.useCallback<MapEvent>(() => {
    closePopup();
    _WORKAROUND_showList.current = !_WORKAROUND_showList.current;
    forceUpdate({});
    // setShowList(!showList);
  }, [
    // setShowList,
    // showList,
    forceUpdate,
    closePopup,
  ]);

Sorry, thought I did 🤦 now it’s properly published in 4.8.6.

I think these changes are not in the current npm release. Browsing the master branch commits, it seems like the PR changes were undone. Does anyone know why?

I can also use the ref workaround but that doesn’t seem ideal, right?