I’m having a problem with fetching data from my api, and displaying it on a web page. I am getting this error : “items.map is not a function”. Im not sure whether this is a problem with this code or maybe my code for my get request in the api, I’ll post both codes just in case.
I’ll paste my code below without the link to my api.
Thanks,
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
}
}
componentDidMount() {
fetch(" api link ")
.then(res => res.json())
.then(json => {
this.setState({ isLoaded: true, items: json });
}).catch((err) => {
console.log(err);
});
}
render() {
const { isLoaded, items } = this.state;
if (!isLoaded)
return <div>Loading...</div>;
return (
<div className="App">
<ul>
{items.map(item => (
<li key={item.oid}>
Name: {item.rows.productName} | Condition: {item.rows.productCondition}
</li>
))}
</ul>
</div>
);
}
}
export default App;
Api code:
async function getComments(req) {
let status = 500, data = null;
try {
const sql = 'SELECT * FROM products';
const rows = await db.query(sql);
if (rows) {
status = 200;
data = {
rows,
};
} else {
status = 204;
}
} catch (e) {
console.error(e);
}
return { status, data };
}
app.get('/demo/api_project', async (req, res) => {
const { status, data } = await getComments(req);
res.status(status);
if (data) res.json(data);
else res.end();
})