I have a code which I pass it to the onClick event and I want it to be run 3 times: (this code basically choose a random product from products and then by Hooks I update the state to show it in the shop cart and here actually instead of one I'm planing to show 3 random products. so I was thinking is there way to simply fire onClick 3 times with one click. )
const onRandom = () => {
const randomItem = products[Math.floor(Math.random() * products.length)];
const exist = cartItems.find((x) => x.id === randomItem.id);
if (exist) {
setCartItems(
cartItems.map((x) =>
x.id === randomItem.id ? { ...exist, qty: exist.qty + 1 } : x
)
);
} else {
setCartItems([...cartItems, { ...randomItem, qty: 1 }]);
}
};
I have used numourous ways but none of them seems working ...
const onRandom = () => {
const randomItem = products[Math.floor(Math.random() * products.length)];
const exist = cartItems.find((x) => x.id === randomItem.id);
if (exist) {
setCartItems(
cartItems.map((x) =>
x.id === randomItem.id ? { ...exist, qty: exist.qty + 1 } : x
)
);
} else {
setCartItems([...cartItems, { ...randomItem, qty: 1 }]);
}
onRandom2();
};
const onRandom2 = () => {
const randomItem2 = products[Math.floor(Math.random() * products.length)];
const exist2 = cartItems.find((x) => x.id === randomItem2.id);
if (exist2) {
setCartItems(
cartItems.map((x) =>
x.id === randomItem2.id ? { ...exist2, qty: exist2.qty + 1 } : x
)
);
} else {
setCartItems([...cartItems, { ...randomItem2, qty: 1 }]);
}
};
I have also used for and while and changed the const to var and still I'm getting one random product and there is even no error.
maybe I'm missing something about state implication.