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

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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