ChromeBrowser
ChromeBrowser

Reputation: 219

How to use the same variable in two useStates?

import {useState} from 'react'

const CartItem = (props) => {
  const [quantity, setAddQuantity] = useState(1);
  const [, setSubQuantity] = useState(0)

  const addquantityHandler = (event) => {
    setAddQuantity(quantity+1)
  }

  const subquantityHandler = (event) => {
    setSubQuantity(quantity-1)
  }

  return (
    <div>
      <div>CartItem</div>
      <div>{props.title}</div>
      <button onClick={addquantityHandler}>Add One</button>
      <button onClick={subquantityHandler}>Subtract One</button>}
      <p>Quantity : {quantity}</p>
    </div>
  )


}

export default CartItem;

I am starting to learn React. Is there any way to subtract quantity using setSubQuantity. Is this impossible to do as quantity was declared in a different useState?

Upvotes: 0

Views: 42

Answers (2)

Aniket Agarwal
Aniket Agarwal

Reputation: 308

You can achieve this using only one useState.

const [quantity, setQuantity] = useState(1)
 
const addquantityHandler = (event) => {
    setQuantity(quantity+1)
}

  const subquantityHandler = (event) => {
    setQuantity(quantity-1)
}

Upvotes: 2

Quentin
Quentin

Reputation: 943564

How to use the same variable in two useStates?

You can't, and you shouldn't. If you want to track the state of a thing then put that thing in one state variable.

Instead have each of your click handler functions call setAddQuantity with the new value (and rename setAddQuantity to setQuantity.

Upvotes: 1

Related Questions