0

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.

Dran Dev
  • 529
  • 3
  • 20
  • Also, when I `console.log(posts_data)` it really gives me all the data from the api call. – Dran Dev Nov 10 '20 at 18:05
  • What does ```console.log(data)``` and ```console.log(posts_data)``` output? – yudhiesh Nov 10 '20 at 18:06
  • @yudhiesh `console.log(data)` says `Response {type...` and `console.log(posts_data)` gives me an array for all the posts from the api - `[0:{id:1, title: 'aaaaa'...}]` – Dran Dev Nov 10 '20 at 18:12

1 Answers1

0

setPosts sets the data asynchronously. That is why the console.log statement gets executed even before the setPosts finishes its job of setting the fetched content. You can do this instead.

import React, { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  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);
    setImmediate(() => {
      console.log(posts);
    })
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

UPDATE: You can do this for mapping out the posts...

<div className="container-fluid mt-3">
    <h1 className="text-white">Posts</h1>
    <div>{posts && posts.map(post => {
        return <p>asdasd</p>
    })}</div>
</div>
Ravi Garg
  • 1,378
  • 12
  • 23
  • Thanks a lot. I followed the code you gave me but it's still not appearing in the console. Also the mapping part doesn't display anything too. – Dran Dev Nov 10 '20 at 18:15
  • Are you passing data from parent? – Ravi Garg Nov 10 '20 at 18:16
  • Watch this: https://codesandbox.io/s/gifted-matsumoto-2x8lg – Ravi Garg Nov 10 '20 at 18:17
  • 1
    This issue is **well-covered** by previous questions and answers on this topic. Please mark duplicates as duplicates, rather than posting answers. Help in the comments if you want to (that's always a great thing to do). – T.J. Crowder Nov 10 '20 at 18:17
  • @T.J.Crowder You should first read the question and find the actual problems in UPDATE 1 and UPDATE 2 before marking the question as duplicate just based on the first few lines. The problem should be solved, whenever a question is being asked here. It's the duty of every person including me to read and understand the real problem of the asker. – Ravi Garg Nov 10 '20 at 18:25
  • 1
    It's all working now! :) Thank you for everyone's help. Sorry for all the confusion, I just tried using React last night and coming from Vue, this is really different. Thank you all for the help! – Dran Dev Nov 10 '20 at 18:25
  • 1
    @spycbanda - It's also a duty not to fill the site with repetitive questions, as you [instructed the OP to](https://stackoverflow.com/questions/64774001/usestate-not-saving-data?noredirect=1#comment114526423_64774001). Sometimes we just help in comments. – T.J. Crowder Nov 10 '20 at 18:26
  • 1
    No issue @DranDev The community of React is very helpful and I assure you that you would learn React very quickly. Welcome to the community and all the best! – Ravi Garg Nov 10 '20 at 18:27
  • 1
    @spycbanda thank you so much once again! God bless! :) – Dran Dev Nov 10 '20 at 18:28