I'm struggling over here when trying to access nested arrays from a fetched json file.
It's all great until I get to the subarrays.
JSON
{
"id": 001,
"name": "Tom",
"description": "test1",
"colors": [{
"main": "green",
"secondary": "red"
}]
},
{
"id": 002,
"name": "Sam",
"description": "test2",
"colors": [{
"main": "blue",
"secondary": "yellow"
}]
}
JSX
export class UserOverview extends React.Component {
constructor(props) {
super(props);
this.state = {
product: [],
isLoaded: false,
}
}
componentDidMount() {
fetch('https://localhost:3000/api')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
product: json,
})
});
}
render() {
var { isLoaded, product } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
}
else {
return (
<ul>
{product.map(product => (
<li key={product.id}>
Name: {product.name} | Shape: {product.description}
</li>
))}
</ul>
);
}
}
}
export default UserOverview;
Rendering the ID, name and description works fine. But for some reason I can't access then nested arrays, tried different stuff but I'm a bit lost.
In this case, I am trying to render the main colours for the 2 results (Tom and Sam), what is the best way to access these nested arrays?
Any help would be greatly appreciated.
product.colors[0].main? Or how do you access the colors array precisely?