Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – How to loop through an array over and over again in React

Imagine I have an array of objects like this:

const items = [
    {name: "item 0"},
    {name: "item 1"},
    {name: "item 2"}
]

And a component like this:

const [currentItemIndex, setCurrentItemIndex] = useState(0)

setInterval(function () {
   if (currentItemIndex < 3) {
      setCurrentItemIndex(currentItemIndex + 1);
   } else {
      clearInterval();
   }
}, 5000);
   
return (
    <div>
        <p> {items[currentItemIndex].name} <p>
    </div>
)

I want to update currentItemIndex every 5 seconds so the div shows next item, and if it reaches the end, it should start over: 0, 1, 2, 0, 1, 2, 0, 1, 2 ....

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is: it loops correctly the first time, but after reaching the end, it shows the first item for a fraction of a second and then goes to the last item: 0, 1, 2, 0 (really quick to) 2.

What I’m doing wrong?
I searched for this, but every article is talking about "how to prevent infinite loops", not "how to use them"!

>Solution :

You can do it with useEffect and with setTimeout like this:

const items = [{ name: "item 0" }, { name: "item 1" }, { name: "item 2" }];

const App = () => {
  const [currentItemIndex, setCurrentItemIndex] = React.useState(0);

  React.useEffect(() => {
    setTimeout(
      () => setCurrentItemIndex((currentItemIndex + 1) % items.length),
      1000
    );
  }, [currentItemIndex]);

  return (
    <div>
      <p> {items[currentItemIndex].name} </p>
    </div>
  );
};

// export default App;

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading