I’m pretty new to react, and I am trying to make an Increment and decrement component in in my product screen. The issue that I’m having is that I would like it to only be able to increment if the there are that many items in stock, but when I try to do this the component stops showing the number associated with amount of the item chosen. I would really appreciate any help or guidance on how to do this.
Thank you!
ProductScreen.js
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { detailsProduct } from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import { IconContext } from 'react-icons';
import { FiPlus, FiMinus } from 'react-icons/fi';
export default function ProductScreen(props) {
const dispatch = useDispatch();
const productId = props.match.params.id;
const [qty, setQty] = useState(1);
const productDetails = useSelector((state) => state.productDetails);
const { loading, error, product } = productDetails;
const handleQuantity = (type) => {
if (type === "dec") {
qty > 1 && setQty(qty - 1);
}else if(product.countInStock >= product.qty){
setQty(qty + 1);
}
};
return (
<div>
{loading ? (
<LoadingBox></LoadingBox>
) : error ? (
<MessageBox variant="danger">{error}</MessageBox>
) : (
<div>
<Link to="/body">Back to result</Link>
<div className="row top">
<div className="col-1">
<div className="card card-body">
<ul>
<li>
<div className="row">
<div>Status</div>
<div>
{product.countInStock > 0 ? (
<span className="success">In Stock</span>
) : (
<span className="danger">Unavailable</span>
)}
</div>
</div>
</li>
{product.countInStock > 0 && (
<>
<li>
<div className="row">
<div>Qty</div>
<div className="AddContainer">
<div className="AmountContainer">
<FiMinus onClick={() => handleQuantity("dec")}/>
<div className="Amount">{product.qty}</div>
<FiPlus onClick={() => handleQuantity("inc")}/>
</div>
</div>
<div>
</div>
</div>
</li>
</>
)}
</ul>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
);
}