Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
How to continously map an array in JavaScript?

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.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

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]} />
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda