Here's my code:
useEffect(() => {
fetchPosts()
}, [])
const [posts, setPosts] = useState([])
const fetchPosts = async () => {
const data = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=10')
const posts_data = await data.json()
setPosts(posts_data)
console.log(posts)
}
From the console.log(posts)
it says []
with a length: 0
inside. However when I console log posts_data
it then gives me all the posts
I got from that api call. Is the setPosts
not working?
UPDATE
I even added:
<div className="container-fluid mt-3">
<h1 className="text-white">Posts</h1>
{posts.map(post => {
<p>asdasd</p>
})}
</div>
And it doesn't display anything.
UPDATE 2
As suggested, I tried fetching the data on the parent component App.js
and then sent it to my Posts.js
component via props:
useEffect(() => {
fetchPosts()
}, [])
const [posts, setPosts] = useState([])
const fetchPosts = async () => {
const data = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=10')
const posts_data = await data.json()
setPosts(posts_data)
}
return (
<Router>
<div className="container-fluid pt-5">
<Navbar/>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/posts" posts={posts} exact component={Posts} />
</Switch>
And in my Post.js
:
function Posts(props) {
return (
<div className="container-fluid mt-3">
<h1 className="text-white">Posts</h1>
{props.posts.map(post => {
return <p key={post.id}>Hello</p>
})}
</div>
)
}
And now it gives me an error:
TypeError: Cannot read property 'map' of undefined
I really have no idea why my first solution didn't worked, since I used this code the other day and it worked flawlessly without any problems. Now, it doesn't store anything (or maybe because of the async stuffs) it doesn't display all the data I got from that api.