I have a textfield which contains text and a button which will then process the text. The Button should not be clickable if the textfield is empty. Therefore I wrote this code:
const [text, setText] = useState("");
const [active, setActive] = useState(false)
function HandleActiveButton(value: string = '') {
setText(value)
if (text.length > 0) {
setActive(true)
console.log(text)
} else {
setActive(false)
console.log(text)
}
}
My textfield and my button:
<TextField
id="outlined-basic"
label="Enter your text to begin"
variant="outlined"
fullWidth
multiline
rows={4}
value={text}
onChange={(e) => HandleActiveButton(e.target.value)}
/>
<LoadingButton variant="contained" disabled={!active} loading={loading} loadingPosition="end" onClick={SendRequest}>Go</LoadingButton>
It kinda works but the problem is that the variable is not updated in time. If I write "ab" the console returns "a" and if I write "xyz" the console returns "xy", etc. This means that the activation and deactivation of the button is not working properly. (e.g. After I paste something I have to type one additional character before the button becomes clickable). Why is this happening? I update the text variable before I check the text length.