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
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}/>
)
}