I will do the counter operation with React, but when I click the buttons, I can’t see the result of increasing or decreasing instantly on the screen. Can you tell me what I should add to this code part?
<Button color="danger" onClick={() => (cartItem.quantity -= 1)}>
-
</Button>
<h3 style={{ background: "lightgrey", width: "100%" }}>
{cartItem.quantity}
</h3>
<Button color="success" onClick={() => (cartItem.quantity += 1)}>
+
</Button>
2
Answers
In React, states are immutable, which means that you cannot change its value directly.
If you are using a function component:
As you can see, I can’t update directly my state counter, but I have to use setCounter().
You can see the official documentation: Here
In React.js you have to update the variables with the help of state’s setter.
For example,
So to update the counter variable value I have to update it with
setCounter
So in your case you have to create
cartItem
stateAnd the Js function is as follows :