Reputation:
I have a problem with my simple React App. I'm able to connect to an API using Axios and can console log. However, I'm not able to output the data inside the DOM. it's empty why?
import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
state = {
fragrances: []
}
componentDidMount() {
axios.get('http://localhost:1337/fragrances')
.then(res => {
const fragrances = res.data;
this.setState({ fragrances });
})
}
render() {
const { fragrances } = this.state;
return (
<div>
{
fragrances.map((fragrance, index) => {
<h2>{fragrance.Name}</h2>
console.log(fragrance);
})
}
</div>
);
}
}
export default App;
Upvotes: 1
Views: 395
Reputation: 195982
You are not returning anything from your map
It should be
fragrances.map((fragrance, index) => {
return Boolean(fragrance.Name) && <h2 key={index}>{fragrance.Name}</h2>
})
As mentioned in the comments you need to use a key when returning lists of components. Here i am using index
but that is a bad practice (read https://reactjs.org/docs/lists-and-keys.html#keys). Hopefully your fragrance
objects have a unique id
which is what you should use.
Upvotes: 3