Blog>
Snippets

Implementing Type Enums

Provide an example of using enums for action types to avoid direct string usage and mitigate problems with type changes by utilizing a single source of truth.
// Define ActionType enum
class ActionType {
  static get LOGIN() { return 'LOGIN'; }
  static get LOGOUT() { return 'LOGOUT'; }
  static get UPDATE_SESSION() { return 'UPDATE_SESSION'; }
}

// Example of using ActionType enum in an action creator
function loginUser(payload) {
  return { type: ActionType.LOGIN, payload };
}

function logoutUser() {
  return { type: ActionType.LOGOUT };
}

// Reducer that handles actions using the ActionType enum
function sessionReducer(state = {}, action) {
  switch (action.type) {
    case ActionType.LOGIN:
      return { ...state, loggedIn: true, user: action.payload };
    case ActionType.LOGOUT:
      return { ...state, loggedIn: false, user: null };
    case ActionType.UPDATE_SESSION:
      return { ...state, ...action.payload };
    default:
      return state;
  }
}
This JavaScript code creates an ActionType class with static properties to simulate an enum. The class ActionType has static getters for different action types such as 'LOGIN', 'LOGOUT', and 'UPDATE_SESSION'. The loginUser and logoutUser functions are action creators that return action objects using the ActionType enum values, avoiding the use of raw strings. Lastly, the sessionReducer takes actions and updates the state based on the action.type, utilizing the ActionType enum to handle the actions, thus serving as a single source of truth for action types and mitigating potential issues with type changes.