Home > Software engineering >  Writing a shorter form of the if statements in this useEffect
Writing a shorter form of the if statements in this useEffect

Time:10-09

Is there a way to write the if statements in this code less repetitive? How do I make it shorter?

  useEffect(() => {
   function addDefaultCards() {
     Object.entries(allCurrencies).map((item) => {
      if (item[0] === "EUR") {
        setCards((prevItems) => [...prevItems, item]);
      }

      if (item[0] === "USD") {
        setCards((prevItems) => [...prevItems, item]);
      }

      if (item[0] === "RUB") {
        setCards((prevItems) => [...prevItems, item]);
      }

      if (item[0] === "INR") {
        setCards((prevItems) => [...prevItems, item]);
      }
   });
  return cards;
}
addDefaultCards();
}, [allCurrencies]);

CodePudding user response:

Looks like you just need an array of currencies to check for inclusion.

const currencies = ['EUR', 'USD', 'RUB', 'INR'];
useEffect(() => {
    Object.entries(allCurrencies).forEach((entry) => {
        if (currencies.includes(entry[0])) {
            setCards((prevItems) => [...prevItems, entry]);
        }
    });
}, [allCurrencies]);

You do not need the extra nested addDefaultCards function, and you should only use .map when constructing a new array one-to-one by returning from the .map callback (which you aren't doing). For side-effects, use forEach or a for loop. You also don't need return cards, since nothing uses addDefaultCards's return value.

CodePudding user response:

First you have to filter the array then call setCards:

useEffect(() => {
   function addDefaultCards() {
     const items = Object.entries(allCurrencies).filter((item) => {
      return ["EUR", "USD", "RUB", "INR"].includes(item[0]);
     });
     setCards((prevItems) => [...prevItems, ...items]);
   }
   addDefaultCards();
}, [allCurrencies])

You can also do it without a wrapper function:

useEffect(() => {
   const items = Object.entries(allCurrencies).filter((item) => {
     return ["EUR", "USD", "RUB", "INR"].includes(item[0]);
   });
   setCards((prevItems) => [...prevItems, ...items]);
}, [allCurrencies])
  • Related