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

218
Visualizações
React State update: updating the state in timer do not update the values correctly

I am trying to render each element in the roles array. This code works in the timer (setInterval) is as follows:

  1. Assigns the duplicate value of the state in let prevRole variable and its corresponding index in the let prevRoleIndex variable.

  2. Renders the string of random characters 10 times iteratively with 50ms delay.

  3. Now the next element in the roles array is assigned to let newRole variable, by adding +1 to previousRoleIndex and then updating the state with newRole variable.

import {useState, useEffect} from 'react'

const roles = ['Web Developer & UX Designer', 'Software Developer / Engineer', 'Blockchain Developer', 'Data Anaylist/ Scientist']

export default function App() {
 
    const [role, setRole] = useState(roles[0])
    const sleep = (value) =>{
        return new Promise(r => setTimeout(r, value));
    }
    const getRandomString = () =>{
        return (Math.random()).toString(36).substring(2);
    }
    useEffect(() => {
        const timer = setInterval(async() => {
            console.log("Timer has started")

            let prevRole = role;
            let prevRoleIndex = roles.findIndex((ele)=>ele===prevRole)
            
            console.log("Previous Role State: "+ prevRole)
            
            for(let i=0; i<10; i++){
                setRole(getRandomString())
                await sleep(50)
            }

            prevRoleIndex = prevRoleIndex+1 >= roles.length? -1: prevRoleIndex
            let newRole = roles[prevRoleIndex+1]
            
            console.log("New Role State: "+ newRole)
            
            setRole(newRole)
          }, 3000);
          return () => clearInterval(timer);
        }, []);
        return(
          <div>
            <h1>{role}</h1>
          </div>
    )
}

The code works fine during first timer iteration and after second iteration the state does not update.

about 4 years ago · Juan Pablo Isaza
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