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

143
Vistas
Cannot map an array outside of the useEffect

I am getting an error in the console as follows:

Cannot read properties of undefined (reading 'map')

I've searched online extensively for the past few hours and all the solutions state that the async call isn't defined and that's why no value is passed to the map. Thing is, it is defined and called with an empty object to force the await. Please could somebody let me know what I'm missing in the below code?

const [product, setProduct] = useState({});

useEffect(() => {
const getProduct = async () => {
  try {
    const res = await publicRequest.get("products/find/" + id);
    setProduct(res.data);
  } catch (err) {}
};
getProduct();

 }, [id]);

This gets a 'Product' object, which contains an array field called colour. I use this to display several options on the page.

{product.colour.map((c) => (
            <FilterColor colour={c} key={c} />
          ))}

When I change the use effect code to console log the res.data.colour, I get the colour values. I don't understand why this map throws this undefined error, when the product is defined as a result of the setProduct call.

I hope someone can help :)

Edit: Other bits of code that will help understanding of the above:

export const publicRequest = axios.create({  baseURL: BASE_URL,});

and this is how I get console.log to display the colours, by changing the useeffect section:

useEffect(() => {
    const getProduct = async () => {
      try {
        const res = await publicRequest.get("products/find/" + id);
        setProduct(res.data);
        console.log(res.data.colour); //this displays an array of colours in the console
      } catch (err) {}
    };
    getProduct();
  }, [id]);

and without using the map() function, I can display data like this: <Title>{product.title}</Title>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This happens because, when first the page is rendered which is before the api fetch has actually completed, your product value is {}, so when you do product.colour.map since it doesn't have any colour property you will get Cannot read properties of undefined error.

So what you need to do is either

const [product, setProduct] = useState({colour: []});

or in your map do

{product?.colour.map((c) => (
        <FilterColor colour={c} key={c} />
      ))}
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