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

294
Visualizações
"Uncaught TypeError: Cannot read properties of undefined (reading FetchApi.js:23 'data')" when refresh the page

When the code runs for the first time, it's mappings data as I wanted. But when I refresh the page it shows an error. Does anyone know how can I fix this error and what causes it?

The code

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const FetchApi = () => {

const [items, setItems] = useState();

useEffect(() => {
    getUser();
}, [])

async function getUser() {
    try {
        const response = await axios.get('https://datausa.io/api/data?drilldowns=Nation&measures=Population');
        setItems(response.data.data)
        return items;
    } catch (error) {
        console.error(error);
    }
}

return (
    <div>
        {
            items.map(item => (
                <li key={item.Year}>
                    {item.Nation}
                </li>
            ))
        }
    </div>
  )
}

export default FetchApi

Output when runs for the first time enter image description here

Error when refresh the page

enter image description here

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

0

I found the problem.

The problem was, "items" is undefined in its default state. It should be

const [items, setItems] = useState([]);

And I think the reason this error shows only when refresh the page was,

when I change the code and save, it changes the html view automatically but the browser only reads the changed JavaScript codes so the const [items, setItems] = useState(); line never reads at first.

But when I refresh the page the code runs from the beginning and it catches that "items" is undefined and shows the error.

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