code updaed for quantity increase decrese
Some checks failed
NPM Installation / build (16.x, ubuntu-latest) (push) Has been cancelled
NPM Installation / build (16.x, windows-latest) (push) Has been cancelled
NPM Installation / build (17.x, ubuntu-latest) (push) Has been cancelled
NPM Installation / build (17.x, windows-latest) (push) Has been cancelled
NPM Installation / build (18.x, ubuntu-latest) (push) Has been cancelled
NPM Installation / build (18.x, windows-latest) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled

This commit is contained in:
ROSHAN GARG 2025-01-22 12:01:31 +05:30
parent 6553a225d5
commit 4d270cb612
2 changed files with 45 additions and 20 deletions

View File

@ -1,15 +1,18 @@
const initialState = { const initialState = {
items: [], items: [],
} }
const cartactionTypes = { const cartactionTypes = {
ADD_TO_CART: 'ADD_TO_CART', ADD_TO_CART: 'ADD_TO_CART',
REMOVE_FROM_CART: 'REMOVE_FROM_CART', REMOVE_FROM_CART: 'REMOVE_FROM_CART',
INCREASE_COUNT: 'INCREASE_COUNT', INCREASE_COUNT: 'INCREASE_COUNT',
DECREASE_COUNT: 'DECREASE_COUNT', DECREASE_COUNT: 'DECREASE_COUNT',
UPDATE_QUANTITY: 'UPDATE_QUANTITY', // New action type
LOAD_CART: 'LOAD_CART', LOAD_CART: 'LOAD_CART',
CLEAR_CART: 'CLEAR_CART', CLEAR_CART: 'CLEAR_CART',
} }
// Action Creators
export const addToCart = (product) => (dispatch, getState) => { export const addToCart = (product) => (dispatch, getState) => {
dispatch({ dispatch({
type: cartactionTypes.ADD_TO_CART, type: cartactionTypes.ADD_TO_CART,
@ -42,6 +45,14 @@ export const decreaseCount = (productId) => (dispatch, getState) => {
localStorage.setItem('cart', JSON.stringify(getState().cart.items)) localStorage.setItem('cart', JSON.stringify(getState().cart.items))
} }
export const updateQuantity = (productId, quantity) => (dispatch, getState) => {
dispatch({
type: cartactionTypes.UPDATE_QUANTITY,
payload: { productId, quantity },
})
localStorage.setItem('cart', JSON.stringify(getState().cart.items))
}
export const loadCart = () => (dispatch) => { export const loadCart = () => (dispatch) => {
const cartItems = JSON.parse(localStorage.getItem('cart')) || [] const cartItems = JSON.parse(localStorage.getItem('cart')) || []
dispatch({ dispatch({
@ -57,6 +68,7 @@ export const clearCart = () => (dispatch) => {
localStorage.removeItem('cart') localStorage.removeItem('cart')
} }
// Reducer
export const cartReducer = (state = initialState, action) => { export const cartReducer = (state = initialState, action) => {
switch (action.type) { switch (action.type) {
case cartactionTypes.LOAD_CART: case cartactionTypes.LOAD_CART:
@ -98,6 +110,15 @@ export const cartReducer = (state = initialState, action) => {
item._id === action.payload && item.count > 1 ? { ...item, count: item.count - 1 } : item, item._id === action.payload && item.count > 1 ? { ...item, count: item.count - 1 } : item,
), ),
} }
case cartactionTypes.UPDATE_QUANTITY:
return {
...state,
items: state.items.map((item) =>
item._id === action.payload.productId
? { ...item, count: action.payload.quantity }
: item,
),
}
case cartactionTypes.CLEAR_CART: case cartactionTypes.CLEAR_CART:
return { return {
...state, ...state,
@ -108,19 +129,14 @@ export const cartReducer = (state = initialState, action) => {
} }
} }
// src/store/cart/selectors.js // Selectors
// Selector to get all cart items
export const selectCartItems = (state) => state.cart.items export const selectCartItems = (state) => state.cart.items
// Selector to get the total count of items in the cart
export const selectCartItemCount = (state) => export const selectCartItemCount = (state) =>
state.cart.items.reduce((total, item) => total + item.count, 0) state.cart.items.reduce((total, item) => total + item.count, 0)
// Selector to get the subtotal (sum of price * count) of items in the cart
export const selectCartSubtotal = (state) => export const selectCartSubtotal = (state) =>
state.cart.items.reduce((total, item) => total + item.price * item.count, 0) state.cart.items.reduce((total, item) => total + item.price * item.count, 0)
// Selector to check if a specific product is already in the cart
export const selectIsProductInCart = (productId) => (state) => export const selectIsProductInCart = (productId) => (state) =>
state.cart.items.some((item) => item._id === productId) state.cart.items.some((item) => item._id === productId)

View File

@ -13,6 +13,7 @@ import {
TableHead, TableHead,
TableRow, TableRow,
useMediaQuery, useMediaQuery,
TextField,
} from '@mui/material' } from '@mui/material'
import ClearIcon from '@mui/icons-material/Clear' import ClearIcon from '@mui/icons-material/Clear'
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
@ -23,7 +24,8 @@ import {
decreaseCount, decreaseCount,
removeFromCart, removeFromCart,
selectCartItemCount, selectCartItemCount,
} from '../../../redux-store/CartStore/ducs' // Adjust this path as per your project structure updateQuantity,
} from '../../../redux-store/CartStore/ducs'
const ShoppingCart = ({ handleTabChange }) => { const ShoppingCart = ({ handleTabChange }) => {
const matches = useMediaQuery('(min-width:1200px)') const matches = useMediaQuery('(min-width:1200px)')
@ -35,7 +37,6 @@ const ShoppingCart = ({ handleTabChange }) => {
// Calculate total GST for the entire cart // Calculate total GST for the entire cart
const totalGST = cartItems.reduce((acc, item) => { const totalGST = cartItems.reduce((acc, item) => {
// console.log(item)
const gstAmount = (item.price * item.GST) / 100 const gstAmount = (item.price * item.GST) / 100
return acc + gstAmount * item.count return acc + gstAmount * item.count
}, 0) }, 0)
@ -48,6 +49,13 @@ const ShoppingCart = ({ handleTabChange }) => {
dispatch(increaseCount(productId)) dispatch(increaseCount(productId))
} }
const handleInputChange = (productId, value) => {
const quantity = parseInt(value, 10)
if (!isNaN(quantity) && quantity > 0) {
dispatch(updateQuantity(productId, quantity))
}
}
const removeCartItemHandler = (productId) => { const removeCartItemHandler = (productId) => {
dispatch(removeFromCart(productId)) dispatch(removeFromCart(productId))
} }
@ -86,11 +94,6 @@ const ShoppingCart = ({ handleTabChange }) => {
> >
<TableCell> <TableCell>
<Box sx={{ display: 'flex' }}> <Box sx={{ display: 'flex' }}>
{/* <img
src={row.product.image[0].url}
alt={row.product.name}
style={{ width: '100px', height: '70px', marginRight: '1rem' }}
/> */}
<Box> <Box>
<Typography fontWeight={600}>{row.name}</Typography> <Typography fontWeight={600}>{row.name}</Typography>
<Box <Box
@ -115,25 +118,31 @@ const ShoppingCart = ({ handleTabChange }) => {
sx={{ sx={{
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
border: '1px solid #6C7275', // border: '1px solid #6C7275',
borderRadius: '4px', borderRadius: '4px',
width: '80px',
justifyContent: 'space-between', justifyContent: 'space-between',
}} }}
> >
<Typography {/* <Typography
onClick={() => handleDecrease(row._id)} onClick={() => handleDecrease(row._id)}
sx={{ cursor: 'pointer', padding: '0.5rem' }} sx={{ cursor: 'pointer', padding: '0.5rem' }}
> >
- -
</Typography> </Typography> */}
<Typography>{row.count}</Typography> <TextField
<Typography type="number"
value={row.count}
onChange={(e) => handleInputChange(row._id, e.target.value)}
size="small"
sx={{ minWidth: '200px', textAlign: 'center' }}
inputProps={{ min: 1 }}
/>
{/* <Typography
onClick={() => handleIncrease(row._id)} onClick={() => handleIncrease(row._id)}
sx={{ cursor: 'pointer', padding: '0.5rem' }} sx={{ cursor: 'pointer', padding: '0.5rem' }}
> >
+ +
</Typography> </Typography> */}
</Box> </Box>
</TableCell> </TableCell>
<TableCell>{row.price}</TableCell> <TableCell>{row.price}</TableCell>