0

I have a list with three string elements, and I would like to use the array elements one by one to update the component <p>{text}</p> at a time interval of 3 seconds.

I found a similar answer here, but I don't want to randomly pick the array elements and I would like to stop after I go throw every array elements.

Rafi
  • 467
  • 6
  • 17

2 Answers2

1

  const [currentIndex, setCurrentIndex] = useState(0);
  const names = ["tony", "elias", "fadi"];


  useEffect(() => {
    if (currentIndex === names.length - 1) {
      console.log("stopping");
      return;
    }
    const interval = setInterval(() => {
      const updatedData = currentIndex + 1;
      setCurrentIndex(updatedData);
    }, 5000);

    return () => clearInterval(interval);
  }, [currentIndex]);


  return (
    <div>
      <p>{names[currentIndex]}</p>
    </div>
  );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
0

You can try the below approach

//replace it with `import` in your code
//import { useState, useRef, useEffect } from 'react'
const { useState, useRef, useEffect } = React

const names = [
    'A', 'B', 'C'
]

function MyComponent() {
    const [nameIndex, setNameIndex] = useState(0); //start with the first name
    const intervalId = useRef();

    const changeName = () => {
        const nextIndex = nameIndex + 1
        if(nextIndex === names.length - 1) {
           clearInterval(intervalId.current);
        }
        if(!names[nextIndex]) {
           return //if the current index does not exist, break the function
        }
        setNameIndex(nextIndex);
    };

    useEffect(() => {
        intervalId.current = setInterval(changeName, 3000);
        return () => clearInterval(intervalId.current);
    }, [changeName])

    return(
        <span>{names[nameIndex]}</span>
    )
}

ReactDOM.render(
  <MyComponent/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • 1
    Thank you for your solution! The solution below from Farhan Mian did the job for me as well. – Rafi Sep 14 '22 at 01:54