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

139
Views
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 answers
Answer question

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