Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

289
Views
"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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!