What I am trying to do: I want to make it so that when you click on a button with the mouse or with enter from the keyboard that you cannot click on it again afterwards. In other words, disable it after pressing the button one time.
Clicking for the second time with the mouse worked, but I can't get it to work with enter.
My code is as follows.
function HomeFood() {
const [food, setFood] = useState(null);
const [calories, setCalories] = useState('');
const [disabled, setDisabled] = useState(false);
async function foodData() {
const result = await axios.get(`link`);
console.log('DATA RESULTS:', result.data);
setFood(result.data)
}
function handleChange(e) {
setCalories(e.target.value);
}
function handleKeyPress(e) {
if (e.key === 'Enter') {
foodData()
}
}
return (
<div className="container">
<section className='food'>
<input
type='number'
onChange={handleChange}
onKeyPress={handleKeyPress}
/>
<button
onClick={() => {
foodData();
setDisabled(true);
}}
disabled={disabled}
>
Click here
</button>
</section>
{food && <FoodNutrients mealsData={food}/>}
</div>
);
}
I tried to use the disabled state in the onKeyPress function, but only get errors. I also tried putting it in the input of the onKeyPress, but again more errors.
Just like the onClick
, invoke setDisabled
in handleKeyPress
:
function handleKeyPress(e) {
if (e.key === 'Enter') {
if (disabled) { // do nothing if already disabled
return;
}
foodData();
setDisabled(true);
}
}