Blog>
Snippets

Enhanced Switch Statements for Action Handling

Demonstrate the use of a switch statement with a default case to manage unknown actions in a function that dispatches actions.
function actionHandler(action, payload) {
  // Enhanced switch statement for action handling
  switch (action) {
    case 'LOGIN':
      // Handle login action
      console.log('Logging in with', payload);
      // Insert login logic here
      break;
    case 'LOGOUT':
      // Handle logout action
      console.log('Logging out');
      // Insert logout logic here
      break;
    case 'REFRESH_PAGE':
      // Handle refresh action
      console.log('Refreshing the page');
      // Insert page refresh logic here
      break;
    // Add more cases as needed
    default:
      // Handle unknown actions
      console.warn('Unknown action:', action);
  }
}
This function 'actionHandler' takes an 'action' string and an optional 'payload' parameter and uses a switch statement to dispatch the corresponding action logic. Each case provides a template for handling distinct actions. The 'default' case warns of unknown actions.