React setState does not work for scene.onPointerObservable, also onMouseDown to canvas not working

I spent a lot of time struggling with these two questions, and until now i still have no idea about them, i would appreciate if someone could help me…
Firstly, i want to use react hooks: setState to set variable when POINTERDOWN and get variable when POINTERUP, however, it does not work. The code is simple in below:
I have this demo code in react hooks:

   const [A, setA] = useState(false);
    useEffect(() => {
        if(scene){
            scene.onPointerObservable.add((pointerInfo) => {
                switch (pointerInfo.type) {
                    case PointerEventTypes.POINTERDOWN:
                        setA(true);
                        break;
                    case PointerEventTypes.POINTERUP:
                        console.log(A);
                        break;
                }
            });
        }

    }, [scene]);

Secondly, it seems that canvas in babylon does not support onMouseDown event, i guess maybe babylon blocked that original canvas pointer event? I want to use this original method because of my first question and i just want to check if it works to bind event to canvas directly;

    const onMouseDown = () => {
        console.log('onmousedown'); //does not trigger
    }
    return <canvas ref={reactCanvas} {...rest} onMouseDown={onMouseDown}/>;

@brianzinn might have some clues :slight_smile:

I think you want touch-action: ‘none’ on your canvas and to track pointer events.

useEffect can return an event that will be called when the dep array changes or component unmounts.

useEffect(() => {
  const pointerObserver = scene.onPointerObservable.add((pointerInfo) => { ... });

  return () => {
  scene.onPointerObservable.remove(pointerObserver);
  }

, [..]);

You need to always clean up when you add observables. Otherwise if that component is tore down (unmounted) that that even handler will keep firing.

Hello @Loukai1991 just checking in has your question been answered?

Yes, that solved my problem. Later on, i found better way to handle this

1 Like