I keep getting error saying the property I’m trying to loop over is undefined. However is I paste the same data in as a variable it works. Also the console.log shows the data is there. This is a component that gets pulled in with Hash Router. What am I doing wrong?
import React from "react";
import { useEffect, useState } from "react";
export default function Icons() {
const [icons, setIcons] = useState([]);
useEffect(() => {
fetch(
"https://.....can't show full url....json/icon-json.json"
)
.then(response => response.json())
.then(data => {
console.log(data);
setIcons(data);
})
.catch(err => {
console.log(err.message);
});
}, []);
console.log(icons);
return (
<div>
<h2>Icons</h2>
{icons.children.map(icon => {
return (
<div key={icon.path} className={"iconDiv"}>
<img src={icon.path} alt="" width="24px" />
<p>{icon.name}</p>
<button
onClick={() => navigator.clipboard.writeText(icon.path)}
className="clipboardButton"
>
<img
src="https://..can't show full url..../icons/copy_neutral.png"
alt=""
width="12px"
/>
</button>
</div>
);
})}
</div>
);
}
2
Answers
This is because you are doing icons is an array, but you are trying to access it as an object.
Try
icons[0].children.map
for example.When you do this:
icons
is an empty array[]
.Then you try to do this
icons.children.map
whereicons.children
isundefined
, thus the error.You probably want to do
icons.map
instead.In case the
data
of yourfetch
returns a nested objects with achildren
field, you probably want to set the icons properly: