skip to Main Content

However, I’m facing issues where when i click one button the value increase by one and when click another button it decrease the value.and the button doesn’t update correctly (not toggling between "add to cart" and remove from cart").

Could someone please guide me on how to correctly implement this functionality? Am I missing something in my approach?

Any help or suggestions would be greatly appreciated. Thank you!

I’m working on a React project where I have a list of items, and I want to implement an "add to cart" functionality. The requirement is that when the user clicks on the "add to cart" button,the cart should increase the cart value by one and when someone click again same button then it should decrease the cart value by one.
I’ve tried implementing this functionality using the following code:

import React, { useState } from "react";
import data from "./Storedata"
import Store from "./Store"
import Menu from "./Menu";

export default function Home() {

const [cart, setCart] = useState(0);

function handleAddToCart() {
  if (!data.isAddToCart) {
    setCart(prevCart => prevCart + 1);
    data.isAddToCart = true;
  } else {
    setCart(prevCart => prevCart - 1);
    data.isAddToCart = false;
  }
  
}

  const products = data.map( item=>{
    const options = item.option ? Object.values(item.option) : undefined;
    return (
      
      <Store 
      key={item.id}
      item={item}
      cart = {cart}
      increCart={handleAddToCart}
      addRemove = {item.isAddToCart}
       />
       )
      
  }

  )
  return (
    <div>
        <div className="products">
         {products}
         <Menu cart={cart} />
        </div>
    </div>
  )
}




import React, { useState } from "react";
export default function Store(props) {

  return (
    <div>
      <div className="storeContainer">
          <button onClick={props.increCart} className="storeButton btn btn-primary">
          {props.addRemove ? 'Remove from Cart' : 'Add to Cart'}
        </button>
          )}
      </div>  
    </div>
  );
}





import { Link } from "react-router-dom";

function Menu({ cart }) {
  return (
    <div >
      <nav className="navbar-expand-lg navbar fixed-top" >

<ul className="LogAcc">
            <li >
                <Link className="LogAcc" to="/cart">
                  Cart({cart})
                </Link>
              </li>
              <li >
                <Link className="LogAcc" to="/account">
                  Account
                </Link>
              </li>
            </ul>    
        
      </nav>
    </div>
  );
}

export default Menu;



export default [
    {
        id: '1',
        image : 'images/Store/shirts1.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        option : {
            color1 :"Black",
            color2:"Blue",
            color3 :"Red",
            color4 :"White",
            color5 : "Brown"

        }
    },
    {
        id: '2',
        image : 'images/Store/shirts2.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        option : {
            color1 :"Black",
            color2:"Blue",
            color3 :"Red",
            color4 :"White",
            color5 : "Brown"

        }
    },
    {
        id: '3',
        image : 'images/Store/shirts3.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        option : {
            color1 :"Black",
            color2:"Blue",
            color3 :"Red",
            color4 :"White",
            color5 : "Brown"

        }
    },
    {
        id: '4',
        image : 'images/Store/shirts4.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },
    {
        id: '5',
        image : 'images/Store/shirts5.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },
    {
        id: '6',
        image : 'images/Store/shirts3.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },
    {
        id: '7',
        image : 'images/Store/shirts5.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },
    {
        id: '8',
        image : 'images/Store/shirts2.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },{
        id: '9',
        image : 'images/Store/shirts4.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        option : {
            color1 :"Black",
            color2:"Blue",
            color3 :"Red",
            color4 :"White",
            color5 : "Brown"

        }
    },{
        id: '10',
        image : 'images/Store/shirts5.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },
    {
        id: '11',
        image : 'images/Store/shirts3.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },{
        id: '12',
        image : 'images/Store/shirts4.jpeg',
        intro: 'Mens Shirts',
        type : 'Shirt',
        price: '119 ',
        isAddToCart: false,
    },

]


2

Answers


  1. You need to store your data in a state and update the state using a setState when you toggle the Add to cart and Remove from cart functionality using a boolean value.

    The reason why you need a state is because simply updating the data object’s property doesn’t cause the component to re-render even though the data object has been mutated and contains the updated property value.

    The re-render will actually cause your component to revisit the values of data. How do you make the component to re-render? Just use a state.

    Login or Signup to reply.
  2. Thank you for the updates that you did to your post. So, the issue is with handleAddToCart function. There you are calling for data.isAddToCart, but your data is an array of objects. You need to provide an item to your function:

      function handleAddToCart(item) {
        if (!item.isAddToCart) {
          setCart(prevCart => prevCart + 1);
          item.isAddToCart = true;
        } else {
          setCart(prevCart => prevCart - 1);
          item.isAddToCart = false;
        }    
      }
    

    And you need to slightly modify your Store component:

    import React, { useState } from "react";
    export default function Store(props) {
    
      return (
        <div>
          <div className="storeContainer">
              <button onClick={() => props.increCart(props.item)} className="storeButton btn btn-primary">
              {props.addRemove ? 'Remove from Cart' : 'Add to Cart'}
            </button>          
          </div>  
        </div>
      );
    } 
    

    So, now you are providing an item and changing the boolean value of that item.
    Hope it will help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search