Home > Software engineering >  Identify each item using keys from array data for add cart button. Reactjs. Redux
Identify each item using keys from array data for add cart button. Reactjs. Redux

Time:03-11

I have a display of products with each name, price and button(add to cart).

The problem is the first data(hoodie white) from my array of products (store component)is the only one that adds up. I can't find a way to identify each array of products when using my handler for dispatch.

Array products sample

const data = {
    products:[
        {   
            id: 1,
            name: 'Hoodie white',
            price: 19.99,

        },
        {
            id: 2,
            name: 'Hoodie black',
            price: 19.99,
        }
    ],

    cart: [],
    total: 0,
}

const ProductComponent=()=>{

    const products= useSelector(state=>state.products);
    const dispatch = useDispatch(0);
    const [productid] = useState(0)
    const purchaseHandler=(e)=>{ 
        dispatch({ type: "PURCHASE", payLoad: products[productid] });
    }
    return(
             products.map((product, i)=>{
            return(
            <>
            <img src={products.image} className="product-image" alt={product.name} />
            <div className='namebtn'>
            <h3 className='product-name-text' key={i}>{product.name}</h3>
            <div key={i}>${product.price}</div>
            <button onClick={purchaseHandler} className="addToCart">Add to Cart</button>
            </div>
            </>
        )})    
    )
    }

CodePudding user response:

Why not pass the product.id to purchaseHandler function

const ProductComponent = () => {
  const products = useSelector((state) => state.products);
  const dispatch = useDispatch(0);
  const purchaseHandler = (e, productid) => {
    dispatch({ type: 'PURCHASE', payLoad: products[productid] });
  };
  return products.map((product, i) => {
    return (
      <>
        <img src={products.image} className="product-image" alt={product.name} />
        <div className="namebtn">
          <h3 className="product-name-text" key={i}>
            {product.name}
          </h3>
          <div key={i}>${product.price}</div>
          <button onClick={(e) => purchaseHandler(e, product.id)} className="addToCart">
            Add to Cart
          </button>
        </div>
      </>
    );
  });
};
  • Related