I call a get request to my api, and then register them to my state with this:
JavaScript
x
12
12
1
useEffect(() => {
2
fetchPosts()
3
},)
4
5
const [posts, setPosts] = useState([])
6
7
const fetchPosts = async () => {
8
const data = await fetch('http://localhost:3000/posts/')
9
const posts_data = await data.json()
10
setPosts(posts_data)
11
}
12
I even tried the axios approach:
JavaScript
1
6
1
await axios.get('http://localhost:3000/posts/')
2
.then(res => {
3
setPosts(res.data)
4
console.log(posts)
5
})
6
If I console.log posts_data
and posts
, it gives me the Object I got from my api:
JavaScript
1
2
1
[{title: "Sample post", desc: "sample desc"}, { }]
2
But whenever I iterate and display it:
JavaScript
1
9
1
<div>
2
{posts.map(post => {
3
<div>
4
<p>{post.title}</p>
5
<h1>asdjasdljaskldjs</h1>
6
</div>
7
})}
8
</div>
9
It doesn’t show up on the page. I even tried adding that random string there asdjasdljaskldjs
and it doesn’t show too. The data is received and stored, but I wonder why it doesn’t display.
Entire component code
JavaScript
1
42
42
1
import React, {useState, useEffect} from 'react'
2
import axios from 'axios'
3
4
function Posts() {
5
6
useEffect(() => {
7
fetchPosts()
8
},)
9
10
const [posts, setPosts] = useState([])
11
12
const fetchPosts = async () => {
13
14
await axios.get('http://localhost:3000/posts/')
15
.then(res => {
16
setPosts(res.data)
17
console.log(posts)
18
})
19
20
// const data = await fetch('http://localhost:3000/posts/')
21
// const posts_data = await data.json()
22
// setPosts(posts_data)
23
// console.log(posts)
24
}
25
26
return (
27
<div className="container-fluid col-lg-7 mt-3">
28
<h1>POSTS</h1>
29
<div>
30
{posts.map(post => {
31
<div>
32
<p>{post.title}</p>
33
<h1>asdjasdljaskldjs</h1>
34
</div>
35
})}
36
</div>
37
</div>
38
)
39
}
40
41
export default Posts
42
I also noticed when I console.log the posts_data
or posts
, it keeps printing over and over again while you’re on the page. Is that normal?
Advertisement
Answer
Your mapping function isn’t returning the JSX. Change your return to:
JavaScript
1
14
14
1
return (
2
<div className="container-fluid col-lg-7 mt-3">
3
<h1>POSTS</h1>
4
<div>
5
{posts.map(post => (
6
<div>
7
<p>{post.title}</p>
8
<h1>asdjasdljaskldjs</h1>
9
</div>
10
))}
11
</div>
12
</div>
13
)
14
You need to surround the returned JSX with parens, not {}
, or you need a return
before the {}
.