'Add Individual Product Clicked to Cart. React Context
I created a cart Array in my Context
const [cart, setCart] = useState([]);
I want to implement an addToCart Button, on Each Button Click, Add the clicked product to cart, and change the button from Add to cart to Remove from cart on that particular Product, not all products.
const addProduct = (product) => {
setCart([
...cart,
{
id: product.id,
drinkName: product.drinkName,
price: product.price,
url: product.url,
},
]);
};
Shop Page
const { products, storeQuery, addProduct } = useProduct();
// Products are coming from Firebase
const addToCart = (product) => {
const newProduct = {
id: product.id,
drinkName: product.drinkName,
price: product.price,
url: product.url,
};
product = newProduct;
console.log("cart Added");
addProduct(newProduct);
console.log(newProduct.id, "Clicked");
};
<SimpleGrid
columns={{ base: 2, md: 4 }}
spacing={{ base: 3, md: 4 }}
>
{products?.map((docsSnapshot) => {
const product = docsSnapshot.data();
return (
<ProductList
key={docsSnapshot.id}
docsSnapshot={docsSnapshot}
product={product}
addProductToCart={(product) => addToCart(product)}
/>
);
})}
</SimpleGrid>
ProductList page
<Button
isFullWidth
onClick={() => addProductToCart(product, docsSnapshot?.id)}
colorScheme="success"
size={"xs"}
>
Add to cart
</Button>
id: undefined, Why is that happening?
I also want to check if a single product in the cart is another component.
Something like this
const inCart = Boolean(
Map through the cart and check if that product is already in the cart
);
So that I can display an incremental button if it exists and display addButton if it doesn't.
Lastly, to access the quantity from any component.
To be able to display a particular product quantity in the productDetails page.
Solution 1:[1]
Calculate cart total.
const total = cart.map(product=>product.price* product?.quantity||1 ).reduce(previousValue, currentValue) => previousValue + currentValue,
0)
console.log({total})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

