Home > Software engineering >  How to continously map an array in JavaScript?
How to continously map an array in JavaScript?

Time:12-12

I am trying to create an alert component in React.JS which would receive one array as props and then loop through all the elements inside and display them in the alert component.

I do not know how to restart the loop when the array map ends.

This is my code:

        useEffect(() => {
                props.messages.map((item, index) => {
                        setTimeout(() => {
                          setMessage(item);
                        }, 5000*index)
                      });
        },[]);

I want to run the loop continuously until the user closes the notification alert.

My guess is to wrap the map inside a while / do while in order to run it until the user closes the notification bar. I am having trouble restarting the loop once the map of the array gets to the last element.

CodePudding user response:

You don't really need to compute an index and reset back to zero.

Add an index state and mounting useEffect hook to increment the index on the 5 second interval. Don't forget to return a cleanup function to clear the interval timer.

const [index, setIndex] = React.useState(0);

useEffect(() => {
  const timerRef = setInterval(() => {
    setIndex(i => i   1);
  }, 5000);
  return () => clearInterval(timerRef);
},[]);

Use a second useEffect hook with a dependency on the index state. When it updates take the index modulus the array length to compute a valid in-range index and update the current message state.

useEffect(() => {
  const { messages } = props;
  setMessage(messages[index % messages.length]);
}, [index]);

However, the second useEffect hook and message state isn't necessary, and could be considered derived state. Derived from the props.messages array and current index state. You can simply use these directly in the rendered alert.

Example:

<Alert message={messages[index % messages.length]} />
  • Related