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

187
Visualizações
Updating React state within JavaScript eval()

I'm writing a live-coding web app in React where the user can write javascript code that moves a player icon through a maze. I want to do this all on the frontend, so I'm using eval() to run the user's code rather than sending it to a backend for evaluation. I am finding some behavior involving eval() and updating graphics/setting state that is causing an issue I can't get around. Below is a simplified version of the functional component in charge of displaying the maze graphics. It accepts the prop code, which updates when the user clicks a "run" button.

export default function MazeEngine(props) {

        const code = props.code;
        const [player, setPlayer] = useState({position: 0});
        const canvasRef = useRef(null);

          useEffect(() => {
            runCode();
          }, [code])

          useEffect(() => {
            draw(canvasRef.current);
          }, [player])

        const move = () => {
           setPlayer((pl) => {..pl, position: pl+1});
        }

        const sleep = (ms) => {
            var start = new Date().getTime(), expire = start + ms;
            while (new Date().getTime() < expire) { }
            return;
          }
        }

        const runCode = () => {
            eval(code);
        }  

        const draw = (ctx) => { // implementation not shown}

    return(
        <canvas ref={canvasRef} style={{width:350, height:350}}>
    )
}

What I have found is that if the user makes multiple calls to move(), all of the calls to setPlayer are batched for after eval() completes. So, for example, if the user writes

move();
sleep(1000);
move();

the display will update after 1 second, with the player moved two spaces forward. I verified that the effect on player is only called once.

Instead, I would like the player to move forward one space, render the new position, wait one second, and move forward another space. That way the user can more easily see the behavior of their algorithm.

using references instead of state

I attempted a different approach where I changed player to being a reference with useRef, and called draw() directly in the move method rather than using useEffect. This gave the same problematic behavior - the canvas does not update until the completion of the eval.

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