Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

447
Views
UseState me muestra el estado anterior

Tengo dos entradas que cambian el texto de una etiqueta P al mismo tiempo, pero el problema es que el render que me muestra siempre es el valor anterior que se guardó. Entiendo que tengo que usar un useEffect para volver a representar el componente y mostrar el valor actual, pero en las entradas handleChange si necesito enviar al SetState que cambia el texto, el valor que se guardó en initialValue. Hasta ahora estoy aprendiendo React y ya probé muchas cosas, pero nada me funciona, ¿cómo podría implementar el useEffect en este caso? Muchas gracias por la ayuda.

 const initialValue = { input1: 0, input2: 0, }; const TestState = () => { const [obj, setObj] = useState(initialValue); const [textChange, setTextChange] = useState("-"); useEffect(() => {}, [obj]); const handleChange = (e) => { setObj({ ...obj, [e.target.name]: e.target.value }); //Basically I need to do this -> setTextChange(e.target.value), but with the value stored in the initialValue. setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2); }; return ( <div> <form> <input type="text" name="input1" onChange={handleChange} /> <input type="text" name="input2" onChange={handleChange} /> </form> <p>{textChange}</p> </div> ); };

https://codesandbox.io/s/practical-mahavira-pd94p?file=/src/TestState.js

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El setter que obtiene de useState (es decir setObj ) no altera inmediatamente el valor/estado del objeto bajo control. La actualización ocurre antes del siguiente render(). Es por eso que su objeto obj parece estar obsoleto.

Tenga en cuenta que no necesita reemplazar el objeto obj en sí mismo, solo está actualizando su contenido. Podrías hacer esto:

 const [obj] = useState(initialValue); ... const handleChange = (e) => { //setObj({ ...obj, [e.target.name]: e.target.value }); obj[e.target.name] = e.target.value; setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!