Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
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

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

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>
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda