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

129
Vistas
React input field value issue
const [inputValue,setInputValue] = useState("")
handleChange = (e)=>{
 setInputValue(e.target.value)
console.log(e.target.value,inputValue)
}

this is a simple input tag onChange function but the thing here inside the handleChange function when am logging the values e.target.value is what am typing on the field and inputValue which is the state am setting is actually empty so if i type let's say 'd' in the input field the value of the state is actualy empty and the next time i type something now it has the value 'd' which i have typed on previously...pls help me solve this

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Yes. State change is async operation. console.log immediately executed. That mean console.log print the inputValue before the state update. That why if doing second its showing previous value.

Better you can detect the state change using useEffect

useEffect(()=>{
  console.log(inputValue)
},[inputValue])
about 4 years ago · Juan Pablo Isaza Denunciar

0

"the thing is that i want to do a search bar and because of this when i type let's say "a" or something search doesn't work because the state value is empty that time."

Setting state is an async process. When you try to log the state immediately after setting it all you're doing is logging the existing state before the component has re-rendered.

@prasanth is correct with their answer that adding a useEffect to watch for changes in the input state is the only way to log that new state.

If you're trying to write a search bar here's a quick contrived solution that filters out animal names from an array.

const { useState } = React;

function Example({ data }) {
  
  // Initialise the input state
  const [ input, setInput ] = useState('');

  // When the input value changes
  // update the state
  function handleChange(e) {
    setInput(e.target.value);
  }

  // `filter` the data using the input state,
  // and then `map` over that array to return
  // an array of JSX
  function getFiltered(input) {
    return data
      .filter(el => el.toLowerCase().includes(input))
      .map(el => <p>{el}</p>);
  }

  return (
    <div>
      <input
        type="text"
        placeholder="Find an animal"
        onChange={handleChange}
        value={input}
      />
      <div>{getFiltered(input)}</div>
    </div>
  );

}

const data=["Alpine Goat","Beaver","Carolina Parakeet","Dragonfish","Eurasian Wolf","Frilled Lizard","Gila Monster","Honduran White Bat","Immortal Jellyfish","Japanese Macaque","Kooikerhondje","Leopard Gecko","Megalodon","Nova Scotia Duck Tolling Retriever","Orb Weaver","Pink Fairy Armadillo","Rhombic Egg-Eater Snake","Satanic leaf-tailed gecko","Tibetan Fox","Umbrellabird","Vervet Monkey","Whoodle","Xoloitzcuintli","Yeti Crab","Zonkey"];  

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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