I use redux - toolkit in my app with createAsyncThunk.
I have some "cart" reducer and inside it I have "CART_CLEARED" action.
"CART_CLEARED" is being called when user press on "Clear Cart" button.
But now, I also have to clear cart when user made order.
So, when user made order, I dispatch "createOrder" thunk (created with createAsyncThunk) and then, in same "cart" reducer, listen for "createOrder.fulfilled" action and I have to do the same thing - clear my cart products.
const initialState = {
products: {};
}
export const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
...some reducers,
CART_CLEARED: (state) => {
state.products = initialState.products
},
},
extraReducers: (builder) => {
builder.addCase(createOrder.fulfilled, (state) => {
state.products = initialState.products
});
},
});
Is it normal practice to move this handler into a separate function? or is there some other solution possible within redux?
const initialState = {
products: {};
}
const CART_CLEARED_HANDLER = (state) => {
state.products = initialState.products
}
export const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
...some reducers,
CART_CLEARED: (state) => CART_CLEARED_HANDLER(state)
},
extraReducers: (builder) => {
builder.addCase(createOrder.fulfilled, (state) => CART_CLEARED_HANDLER(state));
},
});