I am making my first steps with react and I'm struggling with the error message:
this.state.items.map is not a function
I already know that map is only a member of an array but not of objects. In the constructor of my App-class I initialized items[] explicit to an array.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class HelloComponent extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
class App extends Component {
constructor() {
super();
this.state = { items: [] };
}
componentDidMount() {
fetch(`http://example.com/api`)
.then(result => {
this.setState({ items: result.json() });
}
);
}
render() {
var listItems = this.state.items.map(item => <HelloComponent name={item.name} />); // crash!!!
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
{listItems}
</p>
</div>
);
}
}
export default App;
I don't know what happens. I have the suspicion that the call to result.json() may override my array with an promise but I have no idea how to implement it correctly.
componentDidMount(), in thefetch()callback, you set it to the response data. That may or may not be an array.console.logjust to be sure of the datatype.console.log(this.state.items);in the render and watch out for what it prints during the whole loading. I bet you'll see anundefinedvalue or anobject.