0

when I make carousel with react, I want to use useInterval custom hook, but this error maked, I don't know reason

useInterval hooks:

function useInterval (callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick () {
      savedCallback.current();
    }
    if (delay !== null) {
      const id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

where useInterval used in function component

useEffect(() => {
    if (carouselRef.current !== null) {
      console.log(currIndex);
      carouselRef.current.style.transform = `translateX(-${currIndex}00%)`;
      if (currList) {
        console.log('startAuto');
        useInterval(() => {
          handleSwipe(1);
        }, 3000);
      }
    }
  }, [currIndex]);

handleSwipe function

const moveToNthSlide = (index) => {
    setTimeout(() => {
      setCurrIndex(index);
      if (carouselRef.current !== null) {
        carouselRef.current.style.transition = '';
      };
    }, 500);
  };

  const handleSwipe = (direction) => {
    if (isAnimating) {
      return;
    }

    setIsAnimating(true);
    const newIndex = currIndex + direction;

    if (newIndex === carouselList.length + 1) {
      console.log('played slide function1');
      moveToNthSlide(1);
    } else if (newIndex === 0) {
      console.log('played slide function2');
      moveToNthSlide(carouselList.length);
    }
    setCurrIndex((prev) => prev + direction);
    if (carouselRef.current !== null) {
      carouselRef.current.style.transition = 'all 0.5s ease-in-out';
    }

    setTimeout(() => {
      setIsAnimating(false);
    }, 500);
  };

I tried to use custom hooks first time, so I don't understand custom hooks rules perfectly.

0 Answers0