This is my React Component. and when I enter total 6 digits in Otp Input; the onComplete
method is getting invoked which will trigger handleSubmit
function and It should print the latest value of state otp
. But it is just printing 5 digits of input. How to solve this ?
function OtpForm() {
const [otp, setOtp] = useState('');
function handleSubmit() {
console.log(otp);
};
return (
<form>
<MuiOtpInput
value={otp}
onChange={(val) => { setOtp(val); }}
validateChar={(val) => !isNaN(val)}
onComplete={() => { handleSubmit(); }}
length={6}
/>
</form>
);
}
3
Answers
By using
useEffect
with[otp]
as its dependency array, thehandleSubmit
function will be triggered whenever theotp
state changes. This ensures that handleSubmit will have access to the latest value ofotp
. Also, remove the call tohandleSubmit
from theonComplete
prop, as it’s now handled by theuseEffect
hook.In tbis code the setOtp function takes a callback that receives the previous state as an argument. This ensures that you’re using the latest state when updating it. In the onComplete handler, I’ve modified it to pass the previous OTP value to the handleSubmit function.
Try this code:-
React doesn’t update the state until it renders again, and considering changing state is asynchronous, it takes a bit time to update the value, thats why you are not getting the latest value. Best way is to update it using a callback function, so it would reflect the latest value, so your code would be like thisL
}