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

216
Visualizações
Getting error of fetched items after refreshing the page

I am fetching my data from external API as usual and this is the typical way I do it:

Fetch API:

 const [tshirts, setTshirts] = useState([]);

    const fetchData = () => {
        fetch('apiEndpoint')
            .then((response) => response.json())
            .then((data) => {
                setTshirts(data[0].clothes.regular.top); // path to my array
            })
            .catch((error) => {
                console.log(error);
            });
    };
    React.useEffect(() => {
        fetchData();
    }, []);

Map through an array:

const tshirtArray = tshirts.tShirt; // specifying the path
const listItems = tshirtArray.map((item) => <li>{item}</li>);

<ul>{listItems}</ul>

Example of data structure:

[
  {
  id: 1,
  clothes: {
     regular: {
      top: {
        sleeveless: [],
        tShirt: [
          "image-path-here"
          ],
.....
.....
.....

When I first time execute the code it works, but after some time or after refreshing the page I get an error of TypeError: Cannot read properties of undefined (reading 'map')

Why is that undefined? The path is correct and fetching the array should be as well. Can not find the reason of it not working.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't have reputation to comment, so let me try to clarify it for you through an answer. As @sojin mentioned, you cannot use tshirts.Tshirt since your state is of array type and arrays can't be used like objects, meaning that if there was an object of lets say exampleObject = { type: "shirt", color: "white } you could call it with exampleObject.type. Since you have an array of objects in your state (top that you are saving to state is still object which contains tShirt array), you first have to use index (to tell which object you want to use from the state array) and then you can use it like you wanted. For example, in your example there are 1 objects in state array. Array indexes start at 0. So you could do tshirts[0].tShirt to get the tShirt array from that object.

However, I would edit your code a bit. Instead of using tshirtArray constant, just do listItems from your state:

const listItems = tshirts.map((item) =>

  • {item.tShirt[0]}
  • );

    Note: I've just used index 0 here to demonstrate the finding of the first item in tShirt array. If you want to see all tShirt image paths, then you may need to do nested mapping or other similar solutions.

    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