eslint: no-case-declaration - unexpected lexical declaration in case block

47,528

Solution 1

ESLint doesn't like let statements inside case blocks inside a reducer, Why?

This is discouraged because it results in the variable being in scope outside of your current case. By using a block you limit the scope of the variable to that block.

Use {} to create the block scope with case, like this:

case DELETE_INTEREST: {
    let .....
    return (...)
}

Check this snippet:

function withOutBraces() { 
  switch(1){
    case 1: 
      let a=10; 
      console.log('case 1', a); 
    case 2: 
      console.log('case 2', a)
  } 
}
function withBraces() { 
  switch(1){
    case 1: {
      let a=10; 
      console.log('case 1', a); 
    }
    case 2: {
      console.log('case 2', a)
    }
  } 
}
console.log('========First Case ============')
withOutBraces()
console.log('========Second Case ============')
withBraces();

For deleting the element from array, use array.filter, because splice will do the changes in original array. Write it like this:

case DELETE_INTEREST:
    let deleteInterests = state.user.interests;
    let newData = deleteInterests.filter(i => i !== action.payload);
    return { ...state, user: { ...state.user, interests: newData } };

Solution 2

try to encapsulate the inside the case with {} like this look simple example

      case EnumCartAction.DELETE_ITEM: {
           const filterItems = state.cart.filter((item) => item._id !== action.payload)
           return {
                ...state,
                cart: filterItems
           }
      }
Share:
47,528
Josh
Author by

Josh

Updated on December 04, 2021

Comments

  • Josh
    Josh about 1 year

    What is the better way to update state in this context inside a reducer?

    case DELETE_INTEREST:
        let deleteInterests = state.user.interests;
        let index = deleteInterests.findIndex(i => i == action.payload);
        deleteInterests.splice(index, 1);
        return { ...state, user: { ...state.user, interests: deleteInterests } };
    

    ESLint doesn't like let statements inside case blocks inside a reducer, getting:

    eslint: no-case-declaration - unexpected lexical declaration in case block

  • nsandersen
    nsandersen over 3 years
    Why, though? :)
  • PaulCo
    PaulCo about 2 years
    From what I understood, if you declare a variable inside a case block without scoping it with {} your variable will be available in the switch block but will only be assigned in that case block (there's a risk it won't be declared if it doesn't go through that case) eslint.org/docs/rules/no-case-declarations