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

140
Vistas
disabling keyPress for enter on same value multiple times

I have a onChange and onKeyPress events for an input field, where when the user presses enter only I want call the API. And if no change in character then I don't want to trigger the API call.

const [searchValue, setSearchValue] = useState('')

handleChange = (e) => {
  setSearchValue(e.target.value)
}

handleKeyPress = (e) => {
 let charCode = event.keyCode;
    if (charCode === 13) {
      getData();
    }
}


return(
 <input 
  onChange={handleChange}
  onKeyPress={handleKeyPress}
/>
)

So if user types 'a' and press on enter it should call API, but on second time user press enter it should not call API, since no character has been changed . So how can I block that if value is same. I have checked e.target.value !== searchValue inside handleKeyPress but didn't worked

Any help is appreciated

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

0

e.target.value !== searchValue - this didn't work because onChange will call before and set the latest value in state so onKeyPress it always be the same.

Try to do like this:

const App = () => {
  const [searchValue, setSearchValue] = React.useState('')
  const handleKeyUp = ({charCode, target : { value }}) => {
    if (charCode === 13 && searchValue !=value ) {
      console.log("get Data")
    }
    setSearchValue(value)
  }
  return(
      <input keyup={handleKeyUp}/>
  )
}
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