Home > OS >  Is it a bad practice to use constants in switch case in JavaScript
Is it a bad practice to use constants in switch case in JavaScript

Time:12-02

In my React/Redux project I tend to use constants in switch case within reducer, since the name of each action tends to be long and complex, I'm wondering if it's a good practice?

const ACTION_LIST = {
  add: 'ACTION_TYPE/ADD_CUSTOMER',
  remove: 'ACTION_TYPE/REMOVE_CUSTOMER',
  update: 'ACTION_TYPE/UPDATE_CUSTOMER',
};

const reducer = produce((draft, action: IQuickBarActions) => {
  const {type, payload} = action

  switch (type) {
    case ACTION_LIST.add: { // here
      // process the state
      break;
    }
    case ACTION_LIST.remove: {
      // process the state
      break;
    }
    case ACTION_LIST.update: {
      // process the state
      break;
    }
    default:
      // do something
  }
};

CodePudding user response:

Using constants in a switch case within a Redux reducer is a common and generally accepted practice. This approach can help make your code more readable and maintainable, since it allows you to use concise, descriptive constant names in your switch case instead of using the full, complex action type names.

Using constants in this way also has the advantage of making it easier to refactor your code later, if you need to change the names of your actions. Instead of having to update the action type names in multiple places throughout your reducer, you can simply update the constant values in your constant object, and all references to those constants in your reducer will be updated automatically.

Overall, using constants in a switch case within a Redux reducer is a good practice and can help improve the readability and maintainability of your code. However, it's important to make sure that the constant values you use are clear and descriptive, so that it's easy to understand what they represent and how they are being used in your code.

CodePudding user response:

That's a perfectly fine practice — any time you have long string variables that you'll be using multiple times, throwing them in a variable is a good idea, since it'll allow your linter and autocomplete to help you out, and reduce typing. It's also very common with Redux actions, especially if you're exporting and using the same actions variables/object in other files (such as in a middleware, dispatch, etc.).

CodePudding user response:

You can use constants but the way of using it is different for example:-

const ACTION_LIST = {
  add_list: 'ACTION_TYPE/ADD_CUSTOMER',
  remove_list: 'ACTION_TYPE/REMOVE_CUSTOMER',
  update_list: 'ACTION_TYPE/UPDATE_CUSTOMER',
};

because when you use the constant then you don't need to miss the spelling mistake and its more prominent to use also.

  • Related