Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda