I have a backend-API server (FastAPI) where i can post/get/update/delete items in a MongoDB collection. I now want to show these items in an React-Frontend, which fetches the API like shown in this code:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: []
}
}
componentDidMount() {
const url = "http://localhost:8000/items";
fetch(url)
.then(response => response.json())
.then(json => this.setState({ items: json }))
}
render() {
const { items } = this.state;
console.log(items)
console.log(Object.keys(items))
return (
<div className="container">
<div class="jumbotron">
<h1 class="display-4">Items from our API call</h1>
</div>
{/* because we have a dict not an array */}
{Object.keys(items).map((item) => (
<div className="card" key={item._id}>
<div className="card-header">
ITEM #{item.name} {item.type.name}
</div>
<div className="card-body">
PRICE: {item.price}
</div>
</div>
))}
</div>
);
}
}
export default App;
The site doesn't show anything, if i look into Development-Tools it says "Uncaught TypeError: Cannot read properties of undefined (reading 'name')."
I cant figure how to fix this typeerror, the API has this format:
{
"items": [
{
"_id": "6273be87b410b45e0f438df4",
"name": "Fifa22",
"price": 40,
"type": "hardware"
}
]
}