Apprentice Apprentice - 13 days ago 6
Javascript Question

Locale language reducer

I am learning redux by doing a small project. Everything is working fine, but I need to know how I can refactor such code. For this situation, it might be good to use

if conditions
like I have done, but what if I need to handle 7-8 languages? It won't be viable to use
else if for 7 times
. What is the proper way to handle such situation? Is it the right place to ask such question here?

import { FRENCH } from '../../public/messages/fr';
import { ENGLISH } from '../../public/messages/en';

const initialState = {
lang: FRENCH.lang,
messages: FRENCH.messages
};
export const localeReducer = (state = initialState, action) => {
switch (action.type) {
case 'LOCALE_SELECTED':
if (action.locale === 'fr') {
return { ...initialState, lang: FRENCH.lang, messages: FRENCH.messages };
} else if (action.locale === 'en') {
return { ...initialState, lang: ENGLISH.lang, messages: ENGLISH.messages };
} break;
default:
return state;
}
};

Answer

You can nest your case statements if you want:

switch (action.type) {
    case 'LOCALE_SELECTED':
      switch (action.locale) {
        case 'fr':
          return { ...initialState, lang: FRENCH.lang, messages: FRENCH.messages };
        default:
          return { ...initialState, lang: ENGLISH.lang, messages: ENGLISH.messages };
      }
      break;

    default:
      return state;
}

or for readability (especially where there are many cases) break the sub case statements out into separate functions (this is moving towards 'composed reducers' where the state is derived from multiple reducers, which can also be at different levels in the hierarchy).

switch (action.type) {
    case 'LOCALE_SELECTED':
     return localeReducer(action);
      break;

    default:
      return state; 
}