Handling Dynamic Action Types in createReducer
Demonstrate the use of custom action type strings, dynamically creating action handlers inside the createReducer.
import { createReducer } from '@reduxjs/toolkit';
// Custom function to generate action types dynamically
const generateActionType = (base, payload) => `${base}/${payload.toUpperCase()}`;
// Dynamic action creators
const dynamicActionCreator = (baseType, payload) => ({
type: generateActionType(baseType, payload),
payload
});
// Define initial state
const initialState = {};
// Define dynamic reducer
const dynamicReducer = createReducer(initialState, (builder) => {
// We use a placeholder action to dynamically add handlers
builder.addDefaultCase((state, action) => {
// Check if the action type matches the dynamic pattern
if (action.type.startsWith('DYNAMIC/')) {
// Extract the dynamic part from the action type
const dynamicPart = action.type.split('/')[1];
// Apply the corresponding dynamic logic (example: increment number)
state[dynamicPart] = (state[dynamicPart] || 0) + action.payload;
}
});
});
// Export reducer
export default dynamicReducer;
// Usage:
// dispatch(dynamicActionCreator('DYNAMIC', 'increment', 5));
This code snippet illustrates how to create a dynamic reducer using Redux Toolkit's createReducer function. It generates action types dynamically based on a base type and a payload, and uses a default case to handle these dynamic actions. The dynamicActionCreator is a utility to create an action with the dynamically generated type and payload. Then in the dynamicReducer, any action type that starts with 'DYNAMIC/' will be handled and dynamicPart is used to access or update the state based on action type.