I'm following the ReactJS AJAX and APIs tutorial. I wrote a simple API in Spring, then a React component to consume that API at http://localhost:8080
. The API currently returns a list of two items as follows:
[
{brand:"Asus", make:"AAA"},
{brand:"Acer", make:"BBB"}
]
Here's what my component looks like:
import React from 'react';
import ReactDOM from 'react-dom';
import { environment } from '../environment/environment';
export class ComputerList extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: [
{brand: null, make: null}
]
};
}
componentDidMount() {
fetch("http://localhost:8080/computers")
.then(res => res.json())
.then(
(result) => {
// correctly displays the results
console.log(result);
this.setState({
isLoaded: true,
items: result.items
});
},
(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 if(items) {
console.log(items);
// error here: cannot read property "map" of undefined
// because this.state.items is undefined somehow?
return(
<ul>
{items.map(item => (
<li key={item.make}>{item.brand} {item.make}</li>
))}
</ul>
);
}
}
}
At line 24, the results are successfully retrieved and logged.
But at line 54, when I try to map each result to a <li>
item, the TypeError
is thrown because items
is somehow undefined? I've followed the answer to a similar question by initializing items
at line 12, and checking items
at line 48, to no avail.
How can I fix this?