Home > Blockchain >  react button conditional rendering not working
react button conditional rendering not working

Time:06-07

working on a cart app - 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

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?

CodePudding user response:

You should make sure that you are creating a new product object, but not mutating old one.

const product = { ...oldProduct, countInStock: newCountInStock };

instead of

product.countInStock = newCountInStock;

CodePudding user response:

We need more information on this code in my opinion, however I do have an idea where the problem might be.

Problem

I think the problem might be in one of two places (think because i need to see your store to be certain):

  1. in the store (where you are using payload to update your state) because your product.countInStock is somehow not being updated.
  2. in the product.countInStock data type because if it is string or something it will not work

Solution

Use chrome dev tools on product.countInStock in your store to examine on action.

Explanation

Since we have an incomplete code, let me tell you the debugging strategy for this problem.

Lets see the algorithm.

  • You press the add to cart button
  • You send the item (product) into add to cart function
  • It checks if the item is already there
  • If it is not, then send item to your store
  • update your store and then receive it as props (you could just recieve directly, i mean why use props when you have context API)
  • use the products object in your ternary operator

What i am guessing is, you are using context API with the add to cart button (for which i think you should use redux, because of redux being better performing with high frequency data flow).

Now considering the following code:

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

The switch is on the product.countInStock thingy. First of all examine that. Now I would recommend using chrome breakpoints (learn from web dev simplified's youtube channel, learning breakpoints is a lifesaver) to check if it is being updated or not whenever you click the add to cart button. You can also simply console log for the purpose

Just break the problem into multiple pieces and then try to solve where the issue is. Issue is your count not being updated somehow. Something is wrong with the function you are using in your context store. We would need to see that code to examine the problem

  • Related