skip to Main Content

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


  1. In React, states are immutable, which means that you cannot change its value directly.

    If you are using a function component:

    const Counter = () => {
    
       const [counter, setCounter] = useState(0)
    
      return (
        <div>
          <p>Counter is {{counter}}</p>
          <button onClick={() => setCounter(counter+1)} >Increment</button>
        </div>
      )
    
    }
    

    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

    Login or Signup to reply.
  2. In React.js you have to update the variables with the help of state’s setter.

    For example,

    const [counter, setCounter] = useState(0);
    

    So to update the counter variable value I have to update it with setCounter

    So in your case you have to create cartItem state

    <Button color="danger" onClick={() => updateCounter("dec")}>
      -
    </Button>
    
    <h3 style={{ background: "lightgrey", width: "100%" }}>
      {cartItem.quantity}
    </h3>
    
    <Button color="success" onClick={() => updateCounter("inc")}>
      +
    </Button>
    

    And the Js function is as follows :

    const [cartItem, setCartItem] = useState({}); // cart item is an object which contains other fields as well
    const updateCounter = (action) => {
        const data = { ...cartItem };
        action === "inc" ? data.quantity++ : data.quantity--;
        setCartItem(data);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search