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

144
Visualizações
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 Respostas
Responde à pergunta

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 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