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

139
Visualizações
Cannot execute a setter in a loop

I'm trying to write a hero quest type script.

In which we browse an array of events. Either the player moves, or he faces an enemy and a fight begins.

So I wrote my script. The quest and read well from start to finish.

Then, I said to myself, that before going any further I was going to do a test where in the first fight the hero's life bridges drop to zero to test the game over situation.

So in the fightHandle function I drop my hero's life points to zero.

But in my loop, this is not taken into account and the hero's life points constantly remain at 10 points while during the quest he passes X through the combat phase.

I did a lot of tests, but I do not see where my error is something escapes me ...


import React, { useEffect, useState } from "react";
import { character } from "./assets/character/character";

export default function Quest({ quest }) {
  const [player, setPlayer] = useState(character.player);

  const startQuest = (quest) => {
    const nbAction = quest.action.length;

    let i = 1;
    const timer = setInterval(() => {
      let action = quest.action[i];

      console.log("Life point", player.life);

      if (player.life > 0) {
        if (i === nbAction) {
          clearInterval(timer);
          endQuest();
        } else {
          if (action === "move") {
            console.log("player movement");
          } else {
            eventHandler(action);
          }
        }
      } else {
        console.log("GAME OVER");
        clearInterval(timer);
      }
      i++;
    }, 500);
  };

  const eventHandler = (action) => {
    console.log(`Interaction with the element: ${action}`);

    const eventType = character[action].type;

    if (eventType === "statiqueMonster" || eventType === "monster") {
      const eventResolution = fightHandle(player, action);

      if (eventResolution === false) {
        console.log("GAME OVER");
      }
    }
  };

  const fightHandle = (player, action) => {
    console.log("!!!!!!!---FIGHT---!!!!!!!");
    setPlayer((s) => ({ ...s, life: 0 })); 

    if (player.life === 0) {
      return false;
    }
  };

  const endQuest = () => {
    console.log(player);
    console.log("fin de la quête", quest.name);
  };

  useEffect(() => {
    startQuest(quest);
  }, []);

  return (
    <div>
      <h1>Quest</h1>
    </div>
  );
}



about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use useRef instead:

import React, { useEffect, useState } from "react";
import { character } from "./assets/character/character";

export default function Quest({ quest }) {
  //const [player, setPlayer] = useState(character.player);

  const playerRef = useRef(character.player);

  const startQuest = (quest) => {
    const nbAction = quest.action.length;

    let i = 1;
    const timer = setInterval(() => {
      let action = quest.action[i];

      console.log("Life point", player.life);

      if (playerRef.current.life > 0) {
        if (i === nbAction) {
          clearInterval(timer);
          endQuest();
        } else {
          if (action === "move") {
            console.log("player movement");
          } else {
            eventHandler(action);
          }
        }
      } else {
        console.log("GAME OVER");
        clearInterval(timer);
      }
      i++;
    }, 500);
  };

  const eventHandler = (action) => {
    console.log(`Interaction with the element: ${action}`);

    const eventType = character[action].type;

    if (eventType === "statiqueMonster" || eventType === "monster") {
      const eventResolution = fightHandle(player, action);

      if (eventResolution === false) {
        console.log("GAME OVER");
      }
    }
  };

  const fightHandle = (player, action) => {
    console.log("!!!!!!!---FIGHT---!!!!!!!");
    //setPlayer((s) => ({ ...s, life: 0 })); 
    playerRef.current = {...playerRef.current, life: 0};
    if (player.life === 0) {
      return false;
    }
  };

  const endQuest = () => {
    console.log(player);
    console.log("fin de la quête", quest.name);
  };

  useEffect(() => {
    startQuest(quest);
  }, []);

  return (
    <div>
      <h1>Quest</h1>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza 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