React increment and decrement count

696 Views Asked by At
import {
  ProductCycleContextProvider,
  ProductContext,
} from '../contexts/productCycleContext';
class Cart extends Component {
  static contextType = ProductContext;
  constructor(props) {
    super(props);
    this.state = {
      selectedForCart: [],
      checkOut: true,
      grandTotal: undefined,
    };
  }

  async componentDidMount() {
    await axios
      .get('http://localhost:80/newItem/storeIntoCart')
      .then((res) => {
        res.data.map((i) => {
          this.context.setCart(i);
        });
      })
      .catch((e) => alert(e));
  }
  remove = () => {
    console.log('remove');
  };
  increment = (v, i) => {
    axios
      .patch(`http://localhost:80/cart/cartCustomize/${i}`, {
        quantity: v,
      })
      .then((res) => {
        const ind = this.context.cart.findIndex((x) => x._id === res.data._id);
        this.context.cart[ind] = res.data;
      })
      .catch((e) => console.log(e));
  };
  decrement = (v, i) => {};
  render() {
    return (
      <div>
        {this.context.cart &&
          this.context.cart.map((v, i) => {
            return (
              <Container className="mt-5" key={i}>
                <Row>
                  <Col lg={2} md={2} sm={12}>
                    <h5>
                      <b>{v.title}</b>
                    </h5>

                    <img
                      src={v.photo}
                      style={{
                        border: '2px solid black',
                        borderRadius: '5px',
                        width: '100px',
                        height: '80px',
                      }}
                    />
                  </Col>
                  <Col lg={2} md={2} sm={12}>
                    <p>
                      Price:&emsp;&#8377;
                      {v.priceTaxIncluded}
                    </p>
                    <p style={{fontSize: '10px'}}>Tax inclusive</p>
                  </Col>

                  <Col lg={2} md={2} sm={12}>
                    <Row>
                      <Button
                        value={v.quantity}
                        onClick={(e) => {
                          const val = e.target.value;
                          const id = v._id;

                          this.decrement(val, id);
                        }}>
                        -
                      </Button>
                      {v.quantity}
                      <Button
                        value={v.quantity}
                        onClick={(e) => {
                          const id = v._id;
                          let val = Number(e.target.value);
                          let q = val + 1;
                          this.increment(q, id);
                        }}>
                        +
                      </Button>
                    </Row>
                  </Col>
                  <Col lg={2} md={2} sm={12}>
                    <br></br>
                    <Button
                      className="btn btn-warning mt-2"
                      size="sm"
                      onClick={this.remove}>
                      Remove
                    </Button>
                  </Col>
                  <Col lg={2} md={2} sm={12}>
                    {this.state.checkOut && (
                      <>
                        <p>{v.priceTaxIncluded * v.quantity}</p>
                      </>
                    )}
                  </Col>
                  <Col lg={2} md={2} sm={12}></Col>
                </Row>
              </Container>
            );
          })}
      </div>
    );
  }
}

In this code, On click of increment I need to increment the product quantity by one. And that quantity should be multiplied with the price. It is happening but if I increment for the first time then it doesn't show anything and on the second time it increases and shows the previous value and on 3rd time click it shows the value of 2nd click... like that it goes... I should click increment button for 2 times should I use component did update...but to render it for the first time?

1

There are 1 best solutions below

3
On

You shouldn't update the cart property if the ProductContext manually. Instead use a function in the ProductContext which use setState to notify React about a change in the state.

  increment = (v, i) => {
    axios
      .patch(`http://localhost:80/cart/cartCustomize/${i}`, {
        quantity: v,
      })
      .then((res) => {
        this.context.setCartItem(res.data);
      })
      .catch((e) => console.log(e));
  };

In your Provider/Context:

setCartItem(cartItem) {
  const ind = this.state.cart.findIndex((x) => x._id === cartItem._id);
  const updatedCart = [...this.state.cart][ind] = cartItem;

  this.setState(updatedCart);
}