In this project I'm attempting to make a simple Online Shop using React JS. The issue I'm having involves setState and lifecycle. Whenever an item in added to a cart its put into an array of objects. The user can also add more then one of the same item to their shopping cart.
The issue I'm having involves calculating the price of an item. Whenever the user put's an item into their cart the price calculates to 0, but when they add another item the price adds up to having two items.
User adds One $3.00 item the total price comes up to $0.00
User adds Two $3.00 items the total price comes up to $6.00
I can't seem to figure out why it's behaving this way.
Disclaimer. This project is not going to be deployed. This project was created to utilize my skills I've already picked up.
import React from 'react'
import StoreSelection from './StoreSelection';
const Store = ({inventory,cart,setCart,setPrice}) => {
const cart_addItem = (newItem) =>{
let duplicate = false;
let indextochange = 0;
for(let item in cart){
if(cart[item].id === newItem.id){
duplicate = true;
indextochange = item;
}
}
if(duplicate===true){
let newList = [];
for(let item in cart){
newList[item] = cart[item];
}
newList[indextochange].quantity +=1;
setCart(newList);
}else{
newItem.quantity = 1;
setCart([...cart,newItem]);
}
calculatePrice(cart);
}
const calculatePrice = (list) =>{
let newprice = 0;
console.log(list);
for(let item in list){
console.log(list[item].quantity);
newprice = (parseFloat(list[item].price) * list[item].quantity) + newprice;
}
setPrice(newprice);
}
return (
<div>
<StoreSelection inventory={inventory} cart_addItem={cart_addItem}/>
</div>
)
}
export default Store