0

So I have the following component that returns data of a post.

Where I am confused is how is my data undefined in the return statement even though I successfully fetched it. It seems the return is running before my data is fully fetched. How can I fix this? I thought everything in the useEffect ran before the render.

import { useEffect, useState } from "react"
import { useParams } from "react-router-dom"

export default function PostPage() {
    const [ postInfo, setPostInfo ] = useState(null);
    const { id } = useParams();
    useEffect(() => {
        fetch(`http://localhost:4000/post/${id}`)
        .then(response => {
            response.json().then(postInfo => {
                setPostInfo(postInfo)
            });
        });
    }, [])
    console.log("POST info", postInfo)

    return (
        <div className="post-page">
            {/* <div className="image">
                <img src = {`http://localhost:4000/${postInfo.cover}`} alt=""/>
            </div>
            <h1>{postInfo.title}</h1>
            <div dangerouslySetInnerHTML={{__html:postInfo.content}} /> */}
        </div>
    )
}
UsernameNotFound
  • 115
  • 2
  • 3
  • 8
  • When your component is rendered, `postInfo` is null and any attempts to access `postInfo.cover` or `postInfo.content` will result in an error. `postInfo` is only reassigned/populated _asynchronously_. Consider conditionally rendering any nodes that require access to `postInfo` properties. – Terry Feb 26 '23 at 23:38

0 Answers0