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>
))}
CodePudding user response:
The update will be reflected in the next render. That's how react works by design.
Take your example:
const handleClick = (e,selectedItem) => {
console.log(selectedItems) // current state
let newState = [...selectedItems,selectedItem]
setSelectedItems(newState);
console.log(selectedItems) // This won't print the recently updated state, but the same it printed at the beginning of the function
}
Check this: https://stackoverflow.com/a/54069332/4898348
It's unclear why you need selectedItems
to have the updated state right there. You can just simply use newState
instead.