Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

9주차미션-제이 #19

Merged
merged 13 commits into from
Dec 2, 2024
54 changes: 54 additions & 0 deletions 제이-김규리/9주차/mission 1/src/redux/cartSlice.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {createSlice} from '@reduxjs/toolkit';
import MusicData from '../constants/cartItems';

const initialState = {
items: MusicData,
totalCount: 0,
totalPrice: 0,
}

export const cartSlice = createSlice({
name : 'cartfunction',
initialState,
reducers:{
// 음반수량 증가
increase: (state, action) => {
state.items = state.items.map(e => e.id === action.payload ? {...e, amount: e.amount+1}: e);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전개연산자로 복사를 한 뒤에 변경사항만 변경하는 방식이 굉장히 좋은 것 같아요!

},
// 음반수량 감소
decrease: (state, action) => {
state.items = state.items.map(e => e.id === action.payload ? {...e, amount: e.amount-1}: e);
},
// 음반수량이 1보다 작아질 때, 자동 제거
removeItem: (state, action) => {
state.items = state.items.filter(e => e.id !== action.payload);
},
// 장바구니 초기화
clearCart: (state) => {
state.items = [];
state.totalCount = 0;
state.totalPrice = 0;
},
// 전체 수량 계산
calculateTotals: (state) => {
const { totalCount, totalPrice } = state.items.reduce(
(totals, item) => {
totals.totalCount += item.amount;
totals.totalPrice += item.amount * item.price; // 가격 계산
return totals;
},
{ totalCount: 0, totalPrice: 0 } // 초기값
);

state.totalCount = totalCount; // 총 수량 업데이트
state.totalPrice = totalPrice; // 총 가격 업데이트

console.log(`총 수량: ${totalCount}, 총 가격: ${totalPrice}`);
},

}
})

export const {increase, decrease, removeItem, clearCart, calculateTotals} = cartSlice.actions;
//store에서 add, remove, complte 액션을 내보낸다.
export default cartSlice.reducer;
10 changes: 10 additions & 0 deletions 제이-김규리/9주차/mission 1/src/redux/store.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {configureStore} from '@reduxjs/toolkit'
import cartSlice from './cartSlice'
import modalSlice from '../components/modal/modalSlice'

export default configureStore({
reducer : {
cart : cartSlice,
modal: modalSlice
}
})