xxxxxxxxxx
In plain terms, the error occurs when you try to map over an undefined value,
such as an array that has not been initialized or has not yet received data.
xxxxxxxxxx
function MyComponent() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch('/api/data')
.then((res) => res.json())
.then((data) => {
setData(data);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) {
return <p>Data is loading</p>;
}
return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
xxxxxxxxxx
// NOTE - This solution works when your working with REACT-QUERY
const fetchPlanets = async (page) => {
// const [_key, page] = queryKey;
const response = await fetch(`https://swapi.dev/api/planets/?page=${page}`);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
};
const Planents = () => {
const [page, setPage] = useState(2);
//this point did the magic, and enable the [page-state]
//to be seen at the fetch function
const { data, status } = useQuery(["planets", page], () =>
fetchPlanets(page)
);
console.log(data);
return (
<div>
<h2>Planets</h2>
{status === "pending" && <div>Loading Data</div>}
{status === "error" && <div>Error fetching data</div>}
{status === "success" && (
<div>
{data.results.map((planet) => {
return <SinglePlanet key={planet.name} planet={planet} />;
})}
</div>
)}
</div>
);
};