Skip to content
Advertisement

Decrement function in Reactjs doesn’t work

I am using ReactJs and React-dom in 17.02 version.

I had the same problem described in this question: a value to increment and decrement using button. I used the solution proposed, changed my previous code.

From this one:

     handleDecrement = card => {
        let cards = [...this.state.cards];
        let id = cards.indexOf(card);
        cards[id] = {...card };
        cards[id].quantità --;
        this.setState({ cards });
      }

To this one:

     handleDecrement = card => {
        let cards = [...this.state.cards];
        let id = cards.indexOf(card);
        cards[id] = {...card };
        cards[id].quantità = card[id].quantità > 0 ? (card[id].quantità - 1) : 0;
        this.setState({ cards });
      }

But I see this error in the console TypeError: Cannot read properties of undefined (reading ‘quantità’) I know the meaning but I can’t understand WHY I see this error if “quantità” (amount) is a prop set to zero:

    state = {
        cards: [
          {id:0, nome: 'California', prezzo: 1.99, immagine: california, quantità:0},
          {id:1, nome: 'Dragon', prezzo: 3.49, immagine: dragon, quantità:0},
          {id:2, nome: 'Dynamite', prezzo: 2.49, immagine: dynamite, quantità:0},
          {id:3, nome:'Philadelphia', prezzo:0.99, immagine: philadelphia, quantità:0},
          {id:4, nome:'Rainbow', prezzo:2.99, immagine: rainbow, quantità:0},
          {id:5, nome:'Shrimp', prezzo:1.49, immagine: shrimp, quantità:0}
        ]
      }

Advertisement

Answer

You didn’t show where the reference to card comes from in handleDecrement, but somewhere the reference is changed so it won’t work in indexOf. Instead, create a new list and avoid using mutation.

handleDecrement = card => {
  const cards = this.state.cards.map(c => c.id === card.id 
    ? {...c, quantità: Math.max(0, c.quantità - 1)} 
    : c);

  this.setState({ cards });
      }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement