Reputation: 123
I am new to React. I have an array variable but when I call map function it doesn't work. I get "Uncaught (in promise) TypeError: this.state.products.map is not a function"
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
products: []
};
componentDidMount() {
fetch(url)
.then((Response) => {
this.setState({
products: Response.json()
});
})
.catch(err => console.error);
}
}
render() {
return (
<div>
<div className="col-lg-12">
{this.state.products.map(product1 => (
<Button key={product1.id} style={{ color: 'grey', radius: '5px', width: '90px' }}>
{product1.title}
</Button>
))}
<br /><br /><br />
</div>
</div>
);
}
}
export default Category;
Where am I going wrong? Thank you.
Upvotes: 0
Views: 51
Reputation: 45121
Response.json()
is a Promise. MDN. Assuming you are getting an array from the server you need
componentDidMount() {
fetch(url)
.then(res => res.json())
.then((products) => {
this.setState({
products
});
})
.catch(console.error); // because err => console.error is a noop
}
}
Upvotes: 2
Reputation: 819
I guess, when you're getting response the json response isn't array:
products: Response.json()
Could you please, check, if it actually array
Upvotes: 0