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
Error when refresh the page
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.