I'm relatively new to ReactJS and still kind of getting to grips with it. I'm not by trade a front end developer so the below issue I'm having may be common knowledge amongst fellow React developers, but I can't find any other questions directly answering the issue I have here.
I have an API which displays the following category which are pulled from a database:
[{
"category_id": 85,
"name": "STARTERS",
"description": "Served with salad & mint sauce",
"priority": 1
}, {
"category_id": 86,
"name": "TANDOORI DISHES",
"description": "Tandoori dishes are individually marinated in tandoori spices, herbs & yoghurt sauce & cooked in charcoal oven emerging crisp, fragrant & golden red. Served with salad & mint sauce",
"priority": 2
}, {
"category_id": 87,
"name": "TANDOORI MASALA",
"description": "Special Tandoori Masala",
"priority": 3
}]
I'm trying to make a call to this API via a ReactJS project:
import React, { Component } from 'react';
class Api extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://my-api.com/category")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.category_id}>
{item.name} {item.description}
</li>
))}
</ul>
);
}
}
}
export default Api;
The error I'm getting is as follows:
Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
and then it points to the following line from above in the render method:
{item.name} {item.description}
Can anybody point out where I'm going wrong here?
Thanks
resultis the array of items, and notresult.items. You could trythis.setState({ isLoaded: true, items: result });this.state.items.map(..