I have a very simple switch block, and I have a very strict set of options that can possibly be put into it. The switch block is as follows...
const handleOption = (option) => {
setSortBy(option)
switch (option){
case("DAR"):
setTitle('Delivered and Recieved')
case('DCR'):
setTitle('Delivery Completion Rate')
case('POD'):
setTitle('Photo on Delivery Rate')
case('CC'):
setTitle('Call Compliance')
case('SC'):
setTitle('Scan Compliance')
case('FICO'):
setTitle('FICO')
case('cdf'):
setTitle('Customer Feedback')
default:
console.log(option)
setTitle(option)
}
setTitle(option)
}
As you see, I have a console.log statement under the default case. Whenever anything goes into this function expression, it will hit the default and be logged. Thus far I have had every possible case option logged, as every single one hits the default. Meaning, 'DAR', 'DCR', 'POD', all the rest. I'm certainly no expert on Switch cases, I seldom use them, but that's mainly because this exact issue always happens and I don't know why nor where to find the answer
You need a break statement after each case is finished.
const handleOption = (option) => {
setSortBy(option)
switch (option) {
case ("DAR"):
setTitle('Delivered and Recieved');
break;
case ('DCR'):
setTitle('Delivery Completion Rate');
break;
case ('POD'):
setTitle('Photo on Delivery Rate');
break;
case ('CC'):
setTitle('Call Compliance');
break;
case ('SC'):
setTitle('Scan Compliance');
break;
case ('FICO'):
setTitle('FICO');
break;
case ('cdf'):
setTitle('Customer Feedback');
break;
default:
console.log(option)
setTitle(option)
}
setTitle(option)
}
Instead of using switch you could build a little dictionary object, and then reference the values using the key. It's a little less unwieldy.
const obj = {
DAR: 'Delivered and Recieved',
DCR: 'Delivery Completion Rate'
};
function setTitle(data) {
console.log(data);
}
function handleOption(option) {
setTitle(obj[option]);
}
handleOption('DAR');
handleOption('DCR');