Home > Blockchain >  Why Class JSON property is not increasing in jsx?
Why Class JSON property is not increasing in jsx?

Time:10-03

I am in learning phase of react and i am having problem as :

why isn't my json variable "qty" is not increasing when i call increaseqty function on clicking, here is my app.js code :

import react from "react";

class cartitem extends react.Component{
    constructor()
    {
        super();
        this.state = {
            title:"IPhone 13",
            price:100000,
            qty:1
        }   
    }
    increaseqty()
    {
        console.log("this is called");
        this.state.qty  ;
    }
    decreaseqty()
    {
        this.state.qty--;
        return;
    }
    render(){
        return (
            <div>
            <h1>CART</h1>
           <div className="cart-item">
           <div className="left-block"><img/></div>
           <div className="right-block">
           <div className="item-details">
            <div>ITEM:{this.state.title}</div>
            <div>PRICE: {this.state.price}</div>
            <div>QTY:{this.state.qty}</div>
           </div>
           <div className="action-buttons">
           <img src="https://cdn-icons-png.flaticon.com/512/992/992651.png" onClick = {this.increaseqty.bind(this)}/>
           <img src= "https://cdn-icons-png.flaticon.com/512/1828/1828906.png"/>
           <img src="https://cdn-icons-png.flaticon.com/512/1345/1345874.png"/>
           </div>
           </div>
           </div>
           </div>
        )
    }
}
export default cartitem;

thanks for the help in advance!

CodePudding user response:

You can not mutate the state in React as a normal variable. What you must do is to use the setState function provided by React

Something like this should work :

increaseqty()
{
  console.log("this is called");
  this.setState((state) => {
    return { qty: state.qty   1 };
  });
}

CodePudding user response:

Don't modify state directly, you should use setState and in this case you should pass a function which receives the up-to date version of state.

this.setState((state, props) => ({
  qty: state.qty   1
}));

Here is some great documentation about state in components https://reactjs.org/docs/state-and-lifecycle.html

  • Related