Nested conditional statements in React: how to decrement an item count if greater than zero?

71 Views Asked by At

Newbie here! I want to lower a count on an item when a button is pressed, only if the quantity is greater than zero.

An earlier version of my function allowed negative quantities.

decrementItem = (id) => {
    let itemList = this.state.itemList.map(item => {
      item.id === id && item.count--
      return item
      });
    this.setState({
      itemList: itemList
    })
  }

How can I best nest these conditional statements (item.id === id and item.count > 0) before lowering the amount (item.count--)?

decrementItem = (id) => {
    let itemList = this.state.itemList.map(item => {
      item.id === id ? (item.count > 0 && item.count--) : null
      return item
      });
    this.setState({
      itemList: itemList
    })
  }

This block of code returns this error:

Expected an assignment or function call and instead saw an expression
1

There are 1 best solutions below

0
kyun On
decrementItem = (id) => {
    let itemList = this.state.itemList.map(item => {
      item.id === id && (item.count > 0) && item.count-- 
      return item
      });
    this.setState({
      itemList: itemList
    })
  }