mercredi 17 mars 2021

JavaScript/React, best way to prevent a lot of if/else

How to prevent a lot of if/else statements in a function to determine a value?

This question must have been asked before but I can not seem to find a good answer on React specifically after React Hooks have been introduced.

const { yearFilters, rcpFilters } = useSearch();

  const determineValue = () => {
    let finalArray = '';
    if (yearFilters === 'end' && rcpFilters === 'high') {
      return (finalArray = 'value1');
    } else if (yearFilters === 'intermediate' && rcpFilters === 'high') {
      return (finalArray = 'value2');
    } else if (yearFilters === 'begin' && rcpFilters === 'high') {
      return (finalArray = 'value3');
    } else if (yearFilters === 'end' && rcpFilters === 'medium') {
      return (finalArray = 'value4');
    } else if (yearFilters === 'intermediate' && rcpFilters === 'medium') {
      return (finalArray = 'value5');
    } else if (yearFilters === 'begin' && rcpFilters === 'medium') {
      return (finalArray = 'value6');
    } else return (finalArray = 'value7');
  };

  const value = determineValue();

So as you see I am pulling two Hooks out of useSearch(), and depending on those the value should change. Is there a better way than doing it like this? Is a switch/case situation possible here?

Aucun commentaire:

Enregistrer un commentaire