Fetched Object from API doesn’t appear in mapping

Tags: ,



I call a get request to my api, and then register them to my state with this:

useEffect(() => {
    fetchPosts()
},)

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

const fetchPosts = async () => {
    const data = await fetch('http://localhost:3000/posts/')
    const posts_data = await data.json()
    setPosts(posts_data)
}

I even tried the axios approach:

await axios.get('http://localhost:3000/posts/')
.then(res => {
    setPosts(res.data)
    console.log(posts)
})

If I console.log posts_data and posts, it gives me the Object I got from my api:

[{title: "Sample post", desc: "sample desc"}, {...}]

But whenever I iterate and display it:

<div>
    {posts.map(post => {
        <div>
            <p>{post.title}</p>
            <h1>asdjasdljaskldjs</h1>
        </div>
    })}
</div>

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

import React, {useState, useEffect} from 'react'
import axios from 'axios'

function Posts() {

    useEffect(() => {
        fetchPosts()
    },)

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

    const fetchPosts = async () => {

        await axios.get('http://localhost:3000/posts/')
            .then(res => {
                setPosts(res.data)
                console.log(posts)
            })

        // const data = await fetch('http://localhost:3000/posts/')
        // const posts_data = await data.json()
        // setPosts(posts_data)
        // console.log(posts)
    }

    return (
        <div className="container-fluid col-lg-7 mt-3">
            <h1>POSTS</h1>
            <div>
                {posts.map(post => {
                    <div>
                        <p>{post.title}</p>
                        <h1>asdjasdljaskldjs</h1>
                    </div>
                })}
            </div>
        </div>
    )
}

export default Posts

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? enter image description here

Answer

Your mapping function isn’t returning the JSX. Change your return to:

return (
    <div className="container-fluid col-lg-7 mt-3">
        <h1>POSTS</h1>
        <div>
            {posts.map(post => (
                <div>
                    <p>{post.title}</p>
                    <h1>asdjasdljaskldjs</h1>
                </div>
            ))}
        </div>
    </div>
)

You need to surround the returned JSX with parens, not {}, or you need a return before the {}.



Source: stackoverflow