setState Callback in a Functional Component
Tue Jun 29 2021 10:03:32 GMT+0000 (UTC)
Saved by
@hisam
#react.js
#javascript
#react
#usestate
import React, { useEffect, useState } from 'react';
function App() {
const [age, setAge] = useState(0);
updateAge(value) {
setDisplayUsaStudents(
(prevDisplayUsaStudents) => !prevDisplayUsaStudents
);
setAge({prevAge: value});
};
useEffect(() => {
if (age !== 0 && age >= 21) {
// Make API call to /beer
} else {
// Throw error 404, beer not found
}
//the square parentheses with the age state variable inside is called the dependency array. //it tells the useEffect function to listen for any changes to the state of age.
//when age changes, useEffect executes
}, [age]);
return (
<div>
<p>Drinking Age Checker</p>
<input
type="number"
value={age}
onChange={e => setAge(e.target.value)}
/>
</div>
);
}
export default App;
content_copyCOPY
Comments