Created
June 4, 2023 12:54
-
-
Save popeating/bba0d8ecd1964875140d6a4acb97cf52 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSlice } from '@reduxjs/toolkit'; | |
const initialState = { | |
cart: [], | |
totalValue: 0, | |
totalItems: 0, | |
}; | |
const cartSlice = createSlice({ | |
name: 'cart', | |
initialState, | |
reducers: { | |
addToCart: (state, action) => { | |
const itemIndex = state.cart.findIndex( | |
(item) => item.id === action.payload.id | |
); | |
if (itemIndex >= 0) { | |
state.cart[itemIndex].quantity += 1; | |
} else { | |
state.cart.push({ ...action.payload, quantity: 1 }); | |
} | |
state.totalValue += parseFloat(action.payload.price); | |
state.totalItems += 1; | |
}, | |
removeFromCart: (state, action) => { | |
console.log(action); | |
const itemIndex = state.cart.findIndex( | |
(item) => item.id === action.payload.id | |
); | |
console.log(itemIndex); | |
state.cart = state.cart.filter((item) => item.id !== action.payload.id); | |
if (itemIndex >= 0) { | |
const item = state.cart[itemIndex]; | |
console.log('...', item); | |
state.totalValue -= | |
parseFloat(action.payload.price) * action.payload.quantity; | |
state.totalItems -= action.payload.quantity; | |
} | |
}, | |
}, | |
}); | |
export const { addToCart, removeFromCart } = cartSlice.actions; | |
export default cartSlice.reducer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment