0

I have two methods addItem and removeItem. I have also two buttons for these methods via onClick. When I click on addItem button then both methods are triggered, please why?

<button id="a" type="button" onClick={addItem} className="button button-size-small">Add to cart</button>

{items.map((item, index) => {

    <button id="b" type="button" onClick={removeItem(item)}>Delete</button>

})}


const addItem = _ => {
        const item = { id: (new Date).getTime(), userId, choosedFlavor, amount };
        setItems([...items, item]);
    }

const removeItem = item => {
       console.log('remove', item);
    }
3
  • 3
    Because you're calling the removeItem function on every render instead of passing it to onClick. Try () => removeItem(item). Commented Sep 16, 2023 at 13:14
  • 1
    onClick={removeItem(item)}. this is the problem. you are calling the removeItem(). when you use like this you are actually calling the function. Commented Sep 16, 2023 at 13:15
  • Many thanks guys :) It works now! So am I clear? It is rendered every time which means, when click on add button then the react is going to render the page and every placeholder {} is replaced by real value? That means it is rendered according number of cycles. BUT when we use arrow func then it is real callback func that is supposed to be called only when user click. Is it like that? Commented Sep 16, 2023 at 13:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.