-1

Can someone please give me an explanation to why something like this does not work?

const [myState, setState] = React.useState<any>(undefined);


let someOnClickFunction = (e) => { 
  console.log(myState) //undefined on second click
  if(myState !== e.target) { //error myState is undefined 
    console.log("State is different from event")
  }

 setState(e.target)

}

Lets say I click something and someOnClickEvent fires, myState = undefined for the if statement. But when I click and fire someOnClickEvent the second time i expect myState = e.target from first click but actually. myState is still undefined on the second click. I dont really understand why this happens.

it is fired kinda like this:

React.useEffect(() => {
  element.on('click', someOnClickFunction)
},[myState]) 

Specific code for the problem:

     React.useEffect(() => {

    new L.GeoJSON(getGeoJson(), {
      onEachFeature: function (feature, layer) {
        layer.on('click', onLayerClick);
        layer.on('pm:enable', onLayerEditingStart);
        layer.on('pm:disable', onLayerEditingDisable);
        layer.on('pm:update', onLayerEdited);
      }
    }).addTo(features).setStyle({weight: 8});
  }, [mapRef, selectedLayer]);


      let onLayerClick = (e) => {

      if(!(selectedLayer instanceof L.Marker)) { //need this if to have valueof selectedLayer
        selectedLayer.setStyle({color: '#3388ff', weight: 5})
      }
      console.log("selected before")
      console.log(selectedLayer) //undefined -- expected value from last click
      //selectedLayer = e.target;
      setSelectedLayer(e.target)
      console.log("selected after")
      console.log(selectedLayer) //still undefined -- expected value from state set 2 lines above.
  };
Henrik Maaland
  • 210
  • 2
  • 14
  • Can you provide a more complete code snippet? – Phil Oct 21 '20 at 09:00
  • please show more code – linthertoss Oct 21 '20 at 09:00
  • Ok, the actual code is very different from the original question. See https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – you need to keep using `e.target` after setting the state (it won't change immediately.) – Guy Incognito Oct 21 '20 at 09:18

1 Answers1

-1

State change is asynchronous

To follow it you can use useEffect

React.useEffect(()=>{
    console.log("in useEffect ",myState)
},[myState])
Yoel
  • 7,555
  • 6
  • 27
  • 59