I am creating a functionality to add a product to the shopping cart. (Este carro esta en un state centralizado con recoilJs)
The thing is that if I go to a product and add more quantity or reduce its quantity, once added to the cart, it works correctamente
, however, the problem occurs when:
- I have products A and B added to the cart
- I exit the product view and return to product A
- I add another amount of product A
Ocurre el problema
-> adds the product A to the array as new, the array goes from 2 to 3(A, B, A)
My code of the logic of the car is the following:
// React
import React, { useEffect, useState } from 'react';
// Components
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// Recoil
import { cart } from '../../store';
import { useRecoilState, useResetRecoilState } from 'recoil';
// Location state props
import { useLocation } from "react-router-dom";
// Style.sass
import './style.sass';
// Images
const productImage = require('../../assets/images/product/product.png');
const ProductPage = () => {
const notify = () => {
toast('? Wow lo añadiste al carrito!', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
}
const [quantityItems, setQuantity] = useState(0);
const [cartArray, setCart] = useRecoilState(cart);
const location = useLocation();
const { state: data } = location;
const { data:product } = data;
const addToCart = () => {
if(cartArray.length < 1) {
setCart((item) => [
...item,
{
id: product.id,
title: product.title,
quantity: quantityItems
}
])
} else {
cartArray.map((cartItem) => {
if(cartItem.id === product.id) {
console.log('entra aqui I')
let newSetCart = cartArray.map((item) => {
let cartItemCopy = {...item};
if(cartItemCopy.id === product.id) {
cartItemCopy.quantity = quantityItems;
}
return cartItemCopy;
});
setCart(newSetCart);
} else if (cartItem.id !== product.id) {
console.log('entra II')
let newItem = {
id: product.id,
title: product.title,
quantity: quantityItems
}
setCart(cart => [...cartArray, newItem]);
// cartArray.map((item) => {
// console.log('item id ', item.id)
// let cartItemCopy = {...item};
// if(item.id !== product.id) {
// let newItem = {
// id: product.id,
// title: product.title,
// quantity: quantityItems
// }
// setCart(cart => [...cartArray, newItem]);
// }
// })
}
})
}
notify();
}
console.log(useRecoilState(cart));
const setCountHandler = () => {
setQuantity(quantityItems + 1);
}
const removeCountHandler = () => {
if(quantityItems === 0) return;
setQuantity(quantityItems - 1);
}
return(
<div className="product-page-wrapper">
<div className="column-product">
<div className="column-title-product-container">
<div className="title-and-price">
<div className="made-for-text">
<p>MADE FOR Aging Skin</p>
</div>
<div className="daily-mineral-title">
<h1>{product.title}</h1>
{/* <h1>Broad Spectrum</h1> */}
</div>
<div className="lower-text-title">
<p>Use if texture changes got you down and it's time to start anew.</p>
</div>
<div className="price">
<p>${product.price}</p>
</div>
<div className="amount-and-add-button-container">
<div className="quantity-button">
<div className="negative-sign" onClick={removeCountHandler}><p>-</p></div>
<div><p>{quantityItems}</p></div>
<div className="positive-sign" onClick={setCountHandler}><p>+</p></div>
</div>
<div className="add-button" onClick={() => addToCart()}>
<p>ADD TO BAG</p>
</div>
<ToastContainer />
</div>
</div>
</div>
<div className="product-image-container">
<div className="product-image">
<img src={product.image}></img>
</div>
</div>
</div>
<div className="column-description-product">
<div className="main-description-row">
<div className="description-container-container">
<h1>PRODUCT DESCRIPTION</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam arcu orci, consequat et eros id, laoreet consectetur dui.
Curabitur ac risus placerat, fringilla tortor in, porta purus. Donec feugiat tincidunt scelerisque. Cras elit ante, tempor vel sem eget, placerat gravida eros. Nunc tortor justo, consequat nec imperdiet at, aliquet eu libero.
</p>
</div>
<div className="net-weight-container">
<p>Net wt: 17 fl.oz / 50ml</p>
</div>
<div className="adversory-container">
<p>Non-toxic</p>
<p>|</p>
<p>Vegan</p>
</div>
</div>
</div>
</div>
);
}
export default ProductPage;
As data : When I increase or decrease the quantity of a product, I filter it by means of an id of the product in the array
vs the product of the page that comes by props. However, I can't think of how to prevent it from adding to the product if it exists in the array.
The problem occurs because you're already looping through the array with
.map()
and then looping through it again with this:It can be simplified a little more, without the need to go through each element of the array, you just have to find if the product already exists with .findIndex() which returns the position it is in (zero or greater) or minus one if it does not exist.
If it doesn't exist, you add it to the array, and if it already exists, you increment the amount.