728x90
728x90

caseReducers (Redux Toolkit) 속성

들어가며

  • 리덕스 툴킷(Redux Toolkit)caseReducers 속성에 대해 정리해본다.
  • 이 속성을 이용하면 슬라이스 내개별 리듀서 함수에 직접 접근하고 호출할 수 있다.

 

createSlice() 함수와 caseReducers 속성

createSlice() 함수

  • 슬라이스(Slice)를 정의하기 위해 사용된다.
  • 슬라이스는 특정 상태(State)와 그 상태를 변경하는 리듀서(Reducer)들을 한 곳에 모아놓은 것이다.
  • 슬라이스는 자동으로 액션 생성자(Action Creators)액션 타입(Action Types)을 생성해준다.

reducers 옵션

  • createSlice 함수의 reducers 옵션슬라이스의 상태를 변경하는 여러 개의 리듀서 함수를 정의하는 객체이다.
  • 키(Key)액션 이름에 대응하고, 값(Value)은 해당 액션에 대한 리듀서 함수이다.

 

caseReducers 속성

  • 슬라이스 내에 정의된 각 리듀서 함수에 대한 참조를 포함하는 객체이다.
  • 슬라이스 내부에서 다른 리듀서 함수를 직접 호출할 수 있다.
  • 모든 상태 변경 후에 총합을 다시 계산해야 하는 경우, caseReducers를 사용하면 모든 리듀서에서 동일한 로직을 일관되게 적용할 수 있다.
  • caseReducers를 사용하면 코드의 재사용성을 높이고, 상태 업데이트의 일관성을 유지시킬 수 있다.
  • 아래와 같이 사용할 수 있다.
const testSlice = createSlice(
name: 'test',
initialState,
reducers: {
action1: (state, action) => {
// ...
testSlice.caseReducers.action2(state);
// ...
},
action2: (state, action) => {
// ...
}
}
)

 

예제 코드
  • 아래 코드에서 addItem, editItem 액션은 caseReducers 속성을 이용하여 calculateTotals 액션을 직접 호출한다.
const cartSlice = createSlice({
name: 'cart',
initialState: getCartFromLocalStorage(),
reducers: {
// 아이템 추가
addItem: (state, action) => {
const { product } = action.payload;
const item = state.cartItems.find((i) => i.cartID === product.cartID);
if (item) {
item.amount += product.amount;
} else {
state.cartItems.push(product);
}
state.numItemsInCart += product.amount;
state.cartTotal += product.price * product.amount;
// 다른 리듀서에 직접 접근하여 실행하기 (caseReducers) ✅
cartSlice.caseReducers.calculateTotals(state);
toast.success('Item added to cart!');
},
// ...
// 아이템 수정하기
editItem: (state, action) => {
const { cartID, amount } = action.payload;
const item = state.cartItems.find((i) => i.cartID === cartID);
state.numItemsInCart += amount - item.amount;
state.cartTotal += item.price * (amount - item.amount);
item.amount = amount;
// 다른 리듀서에 직접 접근하여 실행하기 (caseReducers) ✅
cartSlice.caseReducers.calculateTotals(state);
toast.success('Cart updated!');
},
// 총합 구하기
calculateTotals: (state) => {
state.tax = 0.1 * state.cartTotal;
state.orderTotal = state.cartTotal + state.shipping + state.tax;
// 로컬 스토리지에 추가
localStorage.setItem('cart', JSON.stringify(state));
},
},
});

 

참고 사이트

 

createSlice | Redux Toolkit

 

redux-toolkit.js.org

 

728x90
728x90

caseReducers (Redux Toolkit) 속성들어가며createSlice() 함수와 caseReducers 속성createSlice() 함수reducers 옵션caseReducers 속성참고 사이트