Building Forward-Compatible Slices with Redux Toolkit
Illustrate the best practices for designing and implementing custom slice reducers that anticipate future changes in JavaScript and Redux patterns.
import { createSlice, current } from '@reduxjs/toolkit';
// Define an initial state that can be easily extended or modified in future
const initialState = {
items: [],
totalAmount: 0
};
// Utilize createSlice to handle state logic in a predictable and modular way
const cartSlice = createSlice({
name: 'cart',
initialState,
reducers: {
// Best practice: Use action creators that can handle new properties without breaking changes
addToCart(state, action) {
const newItem = action.payload;
// Future-proofing: Use immer's 'current' to snapshot state if needed for debug or undo features
console.log('Current state', current(state));
state.items.push(newItem);
state.totalAmount += newItem.price * newItem.quantity;
},
// Supporting function for future removal logic
removeFromCart(state, action) {
const id = action.payload;
const existingItem = state.items.find(item => item.id === id);
if (existingItem) {
state.totalAmount -= existingItem.price * existingItem.quantity;
state.items = state.items.filter(item => item.id !== id);
}
}
// Add more reducers here following the same pattern
}
});
export const { addToCart, removeFromCart } = cartSlice.actions;
export default cartSlice.reducer;
This JavaScript code demonstrates the creation of a Redux cart slice with redux toolkit. The initial state is set up in a manner that allows for easy modifications for future requirements. Action creators like addToCart and removeFromCart are written to be flexible and maintainable.