JS/React - Components lose touch functionality when passed through useEffect/setInterval?

Viewed 22

I am making a simple space shooter style game. The bad guys will be sent to the screen in intervals (similar to tetris).

The bad guys have all their touch functionality working when I pass them in an array manually but when I try to send them to the screen in intervals they lose all touch functionality.

I first tried a useEffect hook with setInterval. The interval would filter the array of bad guys. That was where the problem first popped up. Then, I tried a custom useInterval hook and got the same result.

Lastly - rather than set the state of the array of onscreen villains, I thought I would keep the villains out of the setInterval and just increment indexes, and return a slice of them. This did allow the first villain to gain touch ability but ... I was again frustrated by failure.

Here is the offending code -

aliensArray is the array of alien components for the user to battle.

    function runTheInterval(){
        const difference = slice.right - slice.left;
        if(slice.right < aliensArray.length-1){
            slice.right += 1;
        }
        if (slice.left < slice.right && difference > 3 && difference < 5){
            slice.left += 1;
        }else if (slice.left < slice.right && slice.right === aliensArray.length-1){
            slice.left += 1;
        }
        setSlice(() => {
            return { right: slice.right, left: slice.left }
        })
    }
    
    const interValue = useInterval(runTheInterval, 4000);

----Other code----

    const liveOnScreen = aliensArray.slice(slice.left, slice.right);

 <>
  {liveOnScreen}</>

So the only thing to pass through the interval is the indices of the villains array to be filtered. What am I doing wrong??

Thanks

Here is the custom useInterval hook that I used.

    const intervalRef = useRef(null);
    const savedCallback = useRef(callback);
    useEffect(() => {
      savedCallback.current = callback;
    }, [callback]);
    useEffect(() => {
      const tick = () => savedCallback.current();
      if (typeof delay === 'number') {
        intervalRef.current = window.setInterval(tick, delay);
        return () => window.clearInterval(intervalRef.current);
      }

    }, [delay]);

    return intervalRef;
  }```
0 Answers
Related