Reputation: 3139
So I created this backend json response.
{
"places": [
{
"location": {
"lat": 40.3714624,
"lng": 21.7614661
},
"_id": "5f9bb2ff4fc07350c317500c",
"title": "Alcazar Park",
"description": "A lovely park.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
"creator": "5f9bb2ee4fc07350c317500b",
"__v": 0,
"id": "5f9bb2ff4fc07350c317500c"
},
{
"location": {
"lat": 40.3714624,
"lng": 21.7614661
},
"_id": "5f9bb4f9d92cd5541f5922fc",
"title": "Alcazar Park",
"description": "A beautiful park.",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
"creator": "5f9bb2ee4fc07350c317500b",
"__v": 0,
"id": "5f9bb4f9d92cd5541f5922fc"
},
{
"location": {
"lat": 40.3714624,
"lng": 21.7614661
},
"_id": "5f9bb632d92cd5541f5922fd",
"title": "Train station of Larisa",
"description": "An old but cool train station",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
"creator": "5f9bb2ee4fc07350c317500b",
"__v": 0,
"id": "5f9bb632d92cd5541f5922fd"
}
]
}
Now I want to display in a list just the title of each place in the array. Here is my code for that in React
const DataFetching = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios
.get('http://localhost:5000/api/places/user/5f9bb2ee4fc07350c317500b')
.then(res => {
console.log(res)
setPosts(res.data);
})
.catch((err) => {
console.log(err)
})
}, []);
return(
<div>
<ul>
{
posts.map(post => <li key={post.id}>{post.title}</li>)
}
</ul>
</div>
)
}
export default DataFetching;
However, I am getting this error
How can I fix it?
TypeError: posts.map is not a function
Thanks, Theo
Upvotes: 2
Views: 54
Reputation: 6705
Try this:
setPosts(res.data.places)
posts?.map(post => <li key={post.id}>{post.title}
or:
setPosts(res.data)
posts.places?.map(post => <li key={post.id}>{post.title}
Upvotes: 3