Ensuring Action Types Uniqueness with Object.create(null)
Use Object.create(null) to store action types and ensure there are no name clashes due to accidental prototype inheritance.
const ActionTypes = Object.create(null);
ActionTypes.ADD_ITEM = 'ADD_ITEM';
ActionTypes.REMOVE_ITEM = 'REMOVE_ITEM';
ActionTypes.UPDATE_ITEM = 'UPDATE_ITEM';
// Dispatching an action
function dispatchAction(type, payload) {
// Simple switch-case using the ActionTypes
switch (type) {
case ActionTypes.ADD_ITEM:
console.log('Adding item:', payload);
break;
case ActionTypes.REMOVE_ITEM:
console.log('Removing item:', payload);
break;
case ActionTypes.UPDATE_ITEM:
console.log('Updating item:', payload);
break;
default:
console.log('Unknown action type:', type);
}
}
dispatchAction(ActionTypes.ADD_ITEM, { id: 1, name: 'New Item' }); // Adding item: { id: 1, name: 'New Item' }
Creates an empty object without a prototype using Object.create(null) and assigns unique action types to avoid prototype name clashes. Then defines a dispatchAction function that uses these action types in a switch-case structure. Finally, dispatchAction is called with an ADD_ITEM action type.