简体   繁体   中英

react button conditional rendering not working properly

working on a cart app in a udemy course - the problem is when the quantity gets bought it supposed to make the button disabled but its not working, only showing the add to cart button without disabling it when quantity are zero data.countInStock seems not to be updating

import { Button } from 'react-bootstrap';
import { Card } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import React, { useContext } from 'react';
import Rating from './Rating';
import axios from 'axios';
import { Store } from '../Store';

function Product(props){
 const {product} = props;

const {state , dispatch:ctxDispatch} = useContext(Store);
const {cart: {cartItems}} = state

const addToCartHandler = async (item )=>{
  const existItem = cartItems.find((x)=> x._id === product._id);
   const quantity = existItem ? existItem.quantity+1:1 ; 

  const {data} = await axios.get(`/api/products/${item._id}`);
  if(data.countInStock < quantity){
      window.alert('sorry product is out of stock')
      return;
  }
   ctxDispatch({
       type:'CART_ADD_ITEM' 
       , payload:{...item , quantity},
   });
  };
  

return(

    <Card>


    <Link to={`/product/${product.slug}`}> 
      <img src={product.image} className="card-img-top" alt={product.name} />
    </Link>
    <Card.Body>
    <Link to={`/product/${product.slug}`}>
        <Card.Title>{product.name}</Card.Title>
    </Link>
    <Rating rating={product.rating} numReviews={product.numReviews} />
    <Card.Text>${product.price}</Card.Text>

    {  product.countInStock === 0 ? (

      
      <Button  color="light" disabled={true} >  Out of stock</Button>
      
    ):(
      
      <Button onClick={() => addToCartHandler(product)}>Add to cart</Button>
    )}
  </Card.Body>
</Card>
)}

it's not showing the button out of stock when quantity gets used, What's wrong with the code? full code: https://github.com/basir/mern-amazona/commit/12e565bf6e1859b963729eaba46a5352962fe9e1

full code with backend : https://github.com/basir/mern-amazona/tree/12e565bf6e1859b963729eaba46a5352962fe9e1

Maybe this could start you out. There's no need to make 2 buttons. You can just manipulate the state of the button using your logic

const isOutOfStock = product.countInStock === 0
const buttonText = isOutOfStock ? "Out of stock" : "Add to cart"

<Button color="light" disabled={isOutOfStock} onClick={() => addToCartHandler(product)}>{buttonText}</Button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM