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

289
Vistas
fill an array with useEffect and map()

i am trying to give an array an initial value at every render, This is what i got for the moment

const [activeMarket, setActiveMarket] = useState([]); const Markets = [ 'DE', 'ES', 'FR', 'UK'], i got the values after some filtering in the state.session. const CountryCode = DE, i got the value after some filtering in the state.session.

and i am trying to fill an array at every render using these values this is what i got for the moment

  useEffect(() => {
   markets.map((item) => {
    setActiveMarket([
      ...activeMarket,
      {
        id: item,
        isActiveMarket: true,
        brandName,
      },
    ]);
  });
}, []);

i keep getting an empty array, i don't know what i am doing wrong exactly cause when i did this it worked but only with one object:

  useEffect(() => {
   setActiveMarket([
     ...activeMarket,
     {
       id: countryCode,
       isActiveMarket: true,
       brandName,
     },
   ]);
 }, []);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try creating a new local array in the useEffect and then after mapping it, assign it to the state variable like this:

useEffect(() => {
   const tmpMarkets = markets.map((item) => ({
      id: item,
      isActiveMarket: true,
      brandName
   });
   setActiveMarket(tmpMarkets);
}, []);

Your first snippet is continuously resetting the state variable in each loop, so that's why you are not getting the right array.

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can do this

  useEffect(() => {
   
    setActiveMarket(activeMarket => [
      ...activeMarket,
      ...markets.map((item, i) => ({
        id: item,
        isActiveMarket: i === 0,
        brandName,
      }))
    ]);
  });
}, []);

your first example is not right because you are continuously setting the state and that triggers the rerendering of the component

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