My question is regarding iteration of keys. I want the id with className greenButton
to be applied to the id with className yellowButton
onClick. The problem is that the ´yellowButton´s id is always lagging behind one eventhough they access the same variable.
TL;DR
buttonId
is x where className = greenButton
and x-1 where className = yellowButton
how do I fix this?
const renderTableData = () => {
let id = 1;
return (
<tr>
{days.map((val) => (
<td>
{timeSlot.map((time, i) => {
let buttonId = id ;
if (myBookings().result.includes(id)) {
return (
<button
id={buttonId}
className="yellowButton"
onClick={() => cancelBooking()}
>
{time} {console.log({ buttonId }, { id })} // buttonId is 1 & id is 2
</button>
);
} else if (occupiedSlots().result.includes(id)) {
return (
<button id={buttonId} className="redButton">
{time}
</button>
);
} else {
return (
<button
id={buttonId}
className="greenButton"
onClick={() => {
BookSlot({ id: buttonId });
console.log({ buttonId }); // is 2
}}
>
{time}
{buttonId}
</button>
);
}
})}
</td>
))}
</tr>
);
};
CodePudding user response:
I think let buttonId = id ;
is what causing you this problem. Try using let buttonId = id;
(pre-increment instead of post-increment).
This is what I read somewhere and might answer your question: "preincrement ( i) adds one to the value of i, then returns i; in contrast, i returns i then adds one to it, which in theory results in the creation of a temporary variable storing the value of i before the increment operation was applied".
More reading can be found here