I've seen many answers to this question but I can't make it work for me, I'm trying to have an Add to Menu button for each recipe that I have, and what happens now is that on the first click it creates an empty array, then the second time it works.
const [selectedItems, setSelectedItems] = useState([]);
const handleClick = (e,selectedItem) => {
let newState = [...selectedItems,selectedItem]
setSelectedItems(newState);
console.log(selectedItems)
}
...
...
...
{recipes.reduce(reduceRecipes, []).map((item, index) => (
<Carousel.Item key={item._id}>
<div className="d-flex justify-content-center">
<Row>
{item.map((item, index) => {
return (
<Col sm>
<Card key={item._id} style={{ width: "18rem" }}>
<Card.Img variant="top" src={item.photo_location} />
<Card.Body>
<div className="title-container">
<Card.Title>
{item.name}
</Card.Title>
<p><FcAlarmClock/> {item.prep_time + item.cook_time} minutes</p>
</div>
<Button variant='warning' onClick={(e) => {handleClick(e,item)}}>Add to Menu</Button>
</Card.Body>
</Card>
</Col>
);
})}
</Row>
</div>
</Carousel.Item>
))}