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

214
Vistas
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 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