Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Writing a shorter form of the if statements in this useEffect

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]);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda