Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda