This is because setState
is executed asynchronously. You set clicked
in the OnClick event, and then called the handleOtp
function. In this case, the state hasn't been updated yet, so you get the wrong index on the first click.
You just need to pass index
as a parameter to handleOtp
. setClicked
is no longer needed.
const handleOtp = async (index) => {} <StudentRoute> <div className="row mt-2"> <div className="lessons-menu"> <Menu defaultSelectedKeys={[clicked]} inlineCollapsed={collapsed} style={{ height: "100%" }} > {course.lessons.map((lesson, index) => ( <Item onClick={async () => { setIsLoading(true); setSpin(true); setCheckoutVisibility("none"); checkTransactionStatus(index); setPaymentMethod("kiosk"); setKioskPhoneNumber(""); handleOtp(index); }} key={index} icon={<Avatar>{index + 1}</Avatar>} /> ))} <Menu/> </div> </div> <StudentRoute/>