Nazri AMZ
Nazri AMZ

Reputation: 33

React JS setInterval not working and not resetting my state to 0

I want to ask regarding my setInterval function. I wanted to do something like a carousel auto scroll for my Quotes component.

Problem: The setInterval incremented my currQuote state from 0 to 1 and then stops at 1 and did not set back to 0 as coded in the else statement.

SOLVED: Thank you guys. This was a very silly mistake. I didnt add the dependencies for the useEffect. No wonder it just run once XD

const Quote = () => {
  const [currQuote, setCurrQuote] = useState(0);
  const timerQuote = useRef();

  useEffect(() => {
    timerQuote.current = setInterval(() => {
      if (currQuote < quoteList.length - 1) {
        setCurrQuote(currQuote + 1);
      } else {
        setCurrQuote(0);
      }
      // console.log(currQuote);
    }, 2000);

    // dispose when unmount
    return () => {
      clearInterval(timerQuote.current);
    };
  }, []);

  useEffect(() => {
    console.log(currQuote);
  }, [currQuote]);

return(.......)

Upvotes: 1

Views: 306

Answers (1)

Mahesh Samudra
Mahesh Samudra

Reputation: 1238

Just like Yousaf commented, you need to add the currQuote to the dependency array of the useEffect like this:

 useEffect(() => {
    timerQuote.current = setInterval(() => {
      console.log(currQuote)
      if (currQuote < quoteList.length - 1) {
        setCurrQuote(currQuote + 1);
      } else {
        setCurrQuote(0);
      }
      // console.log(currQuote);
    }, 2000);

    // dispose when unmount
    return () => {
      clearInterval(timerQuote.current);
    };
  }, [currQuote]);

Working sample here: https://codesandbox.io/s/morning-architecture-rgwgoz?file=/src/App.js

Upvotes: 2

Related Questions