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

159
Visualizações
React: why state is updated only at handleChage of input?

I have this Component:

export const DashboardPage = () => {

    const [mounted, setMounted] = useState(false);
    const [currentNumber, setCurrentNumber] = useState(null);
    const [insertedNumber, setInsertedNumber] = useState(null);
    const [result, setResult] = useState(null);
    const [arrayNumbers, setArrayNumbers] = useState([]);

    useEffect(() => {
        const rnd = randomNumber();
        if (!mounted) {
            setCurrentNumber(rnd);
            setMounted(true);
        }
    }, [mounted]);

    const handleChange = (e) => {
        setInsertedNumber(e.target.value);
        
    }

    const handleClick = (e) => {
        e.preventDefault();
        arrayNumbers.push(insertedNumber);
        setArrayNumbers(arrayNumbers);
        setResult("Oops, ritenta! era " + currentNumber)
        if (parseInt(insertedNumber) === parseInt(currentNumber)) {
            setResult("EVVIVA hai vinto!");
        }
    }

    const handleOnSubmit = (e) => {
        e.preventDefault();
    }
    
    return (
        <>
            <h2>Storico tentativi: {arrayNumbers.map(e => e)}</h2>
            <h2>La soluzione è: {currentNumber}</h2>
            <Form onSubmit={handleOnSubmit}>
                <Form.Group controlId="formGTN">
                    <Form.Label>Guess the number:</Form.Label>
                    <Form.Control type="text" onChange={handleChange} />
                </Form.Group>
                <Button variant="primary" type="submit" onClick={handleClick} label="Is it?" />
            </Form>
            <h1>{result}</h1>
        </>
    )
}


export default DashboardPage;

It is a simple "Guess The Number" play.

I have the issue that:

  1. On very first loading of page, I can get into arrayNumbers the only one number I inserted.

  2. From second and other attempts, when I CHANGE the value inside the input, so when I delete previous number, I get state update and I have the previous (and on) numbers. Like if "state" is "back" of one try.

I can see this behavious also in Chrome's Redux plugin. State is update ONLY a step other.

I could move the push into array on onChange, but... If I insert a number of 2 digits I get 2 insert on array (44 will be "4" and "4").

THank you!

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

0

You should never mutate the state and/or update the state without setState. In JavaScript, the Array.push() method mutates the original array. So, in your example, you mutate arrayNumbers but you should add a new element to the array without updating the original one.

Also, listening to the onSubmit event is enough, you don't have to add the onClick event to your submit button. You can move everything from handleClick to handleOnSubmit.

export const DashboardPage = () => {
  const [mounted, setMounted] = useState(false);
  const [currentNumber, setCurrentNumber] = useState(null);
  const [insertedNumber, setInsertedNumber] = useState(null);
  const [result, setResult] = useState(null);
  const [arrayNumbers, setArrayNumbers] = useState([]);

  useEffect(() => {
    const rnd = randomNumber();
    if (!mounted) {
      setCurrentNumber(rnd);
      setMounted(true);
    }
  }, [mounted]);

  const handleChange = (e) => {
    setInsertedNumber(e.target.value);
  };

  const handleOnSubmit = (e) => {
    e.preventDefault();

    setArrayNumbers([...arrayNumbers, insertedNumber]);

    if (parseInt(insertedNumber, 10) === parseInt(currentNumber, 10)) {
      setResult('EVVIVA hai vinto!');
    } else {
      setResult('Oops, ritenta! era ' + currentNumber);
    }
  };

  return (
    <>
      <h2>Storico tentativi: {arrayNumbers.map((e) => e)}</h2>
      <h2>La soluzione è: {currentNumber}</h2>
      <Form onSubmit={handleOnSubmit}>
        <Form.Group controlId="formGTN">
          <Form.Label>Guess the number:</Form.Label>
          <Form.Control type="text" onChange={handleChange} />
        </Form.Group>
        <Button variant="primary" type="submit" label="Is it?" />
      </Form>
      <h1>{result}</h1>
    </>
  );
};
about 4 years ago · Juan Pablo Isaza Relatório

0

For the above component, you might try these changes in the handleClick function:

const handleClick = (e) => {
  e.preventDefault();
  let newArr = [...arrayNumbers];
  newArr.push(insertedNumber);
  setArrayNumbers(newArr);
  setResult('Oops, ritenta! era ' + currentNumber);
  if (parseInt(insertedNumber) === parseInt(currentNumber)) {
    setResult('EVVIVA hai vinto!');
  }
};
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