0

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>
        ))}
  • 1
    The state should be getting updated correctly, but if you are expecting the `console.log` you have inside the `handleClick ` function to print the updated state that won't happen because the state hasn't got updated at that point. Try adding that same console.log outside the function and see if it prints as expected – Nicolas Castellanos Dec 21 '22 at 02:05

1 Answers1

2

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.