I’m a react newbie trying to create a shopping cart. I used redux toolkit to manipulate the cart array.
I’m also trying to increment the quantity counter in the product listing page itself.
Where I’m stuck at is when I try to decrement the quantity of a product in cart page and when the counter reaches 0, redux reducer function deletes the corresponding entry from the cart array. But that creates a problem when I try to access the quantity counter and try to show “Buy now” button again in product listing page.
Code snippets:
export interface Product {
productID: number;
productName: string;
productDesc: string;
productImageURL: string;
originalPrice: number;
offerPrice: number;
quantity: number;
}
const productTile = (data: Product) => {
const toast = useToast();
const dispatch = useAppDispatch();
const cart = useAppSelector((state) => state.cartReducer);
const [showButton, setShowButton] = React.useState<Boolean>(true);
const handleClick = (product: Product) => {
dispatch(addItem(product));
toast({
title: "Item added to cart",
status: "success",
isClosable: true,
duration: 6000,
});
setShowButton(false);
};
const handleDecrement = (product: Product, cartProducts: Product[]) => {
console.log("inside handle decrement");
console.log(product.productID);
cartProducts.map((cartProduct) => {
if (product.productID === cartProduct.productID) {
if (cartProduct.quantity < 2) {
setShowButton(true);
dispatch(decrementQuantity(product));
}
dispatch(decrementQuantity(product));
}
});
};
React.useEffect(() => {
cart.product.map((cartItem) => {
return cartItem.quantity < 1 || cartItem.quantity === null ? (
setShowButton(true)
) : (
<></>
);
});
}, [cart]);
return (
<Box>
<HStack p={2}>
<Image></Image>
<Box w={200} h={75}>
</Box>
<HStack>
{showButton && (
<Button onClick={() => handleClick(data)}>Buy now</Button>
)}
{!showButton && (
<HStack>
<Button onClick={() => handleDecrement(data, cart.product)}>
-
</Button>
<Box>
{cart.product.map((cartItem) => {
return cartItem.productID === data.productID ? (
cartItem.quantity > 0 ? (
<Text>{cartItem.quantity}</Text>
) : (
<Text>0</Text>
)
) : (
<></>
);
})}
</Box>
<Button onClick={() => dispatch(incrementQuantity(data))}>
+
</Button>
</HStack>
)}
</HStack>
</HStack>
</Box>
);
};
export default productTile;
cartTile.tsx
<Button
colorScheme="green"
size="xs"
onClick={() => dispatch(incrementQuantity(cartItem))}
>
+
</Button>
</HStack>
<Text fontSize="x-small" alignSelf="end">
subtotal: {cartItem.quantity * cartItem.offerPrice}
</Text>
</VStack>
</Box>
<Box
w="33%"
display="flex"
flex={0.5}
alignItems="center"
justifyContent="center"
>
<Button
borderWidth={1}
boxShadow="md"
onClick={() => dispatch(removeItem(cartItem))}
>
What I want to know is how can I show my But now button in product tile when an item is deleted by another component?