Akash
Akash

Reputation: 828

Array becoming object when stored in state in react

I am getting some data from my api. In the callback from fetching the data, the data is an array:

const classes = useStyles();

const [posts, setPosts] = useState([]);

useEffect(() => {
    fetch('https://forum-temp.herokuapp.com/api/posts')
        .then((res) => res.json())
        .then((res) => {
            console.log(typeof res.data.docs) // Array
            setPosts(res.data.docs);
        });
}, []); 

Inside the return statement of my functional component -

<div className="post__container">
                    { {posts.map((post, i) => (
                        <MiniPost
                            dp="https://picsum.photos/200"
                            username="blah"
                            time="blah"
                            heading="blah"
                            comments="4"
                            history={history}
                            key={i}
                        />
                    ))} }
    </div>

Upvotes: 0

Views: 41

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

It's because you're double wrapping. React uses only single wrapping. Use only one set of {} like this {posts.map( ... )}:

<div className="post__container">
  {posts.map((post, i) => (
    <MiniPost
      dp="https://picsum.photos/200"
      username="blah"
      time="blah"
      heading="blah"
      comments="4"
      history={history}
      key={i}
    />
  ))}
</div>

Upvotes: 2

Related Questions