Skip to content
Advertisement

TypeError: Cannot read property ‘title’ of undefined Reactjs

I dont know why i have this error!! At first time i dont have any error and its work But when i refresh the page i have this error: TypeError: Cannot read property ‘title’ of undefined or TypeError: Cannot read property ‘image’ of undefined

import React, { useEffect , useState } from 'react';
import Content from './Content';
import NavBar from './NavBar';

    export default function BlogPost() {

    const [post, setPost] = useState([]);
    const [current, setCurrent] = useState(null)

    useEffect(() => {
       const cleanUp = fetch('http://localhost:3000/posts')
       .then( response => response.json())
       .then( post => 
           setPost(post),
           setCurrent(0)
       )
       return () => cleanUp;
    },[])

    function handleClick(index) {
        setCurrent(index)
    }
     

    return (
        <div className="wrapper d-flex align-items-stretch">
          <NavBar posts={post} handleClick={handleClick} />
          { null != current && <Content post={post[current]} />}
        </div>
    )
}

Content.jsx :

export default function Content({post}) {
    return (
       <div>
          <div id="content" className="p-4 p-md-5 pt-5">
        <img src={`/assets/${post.image}`} alt={post.title} />
     <h2 className="mb-4">{post.title}</h2>
     <p>{post.body}</p>
  </div>
       </div>
    )
}

Advertisement

Answer

The issue is here:

<h2 className="mb-4">{post.title}</h2>

here post object will get data from axios call and it will take some time to fetch the data that means on initial render title will not be there. So you have to put some check and access that key only when it is available.

Try something like:

<h2 className="mb-4">{post && post.title}</h2>

Or you can also try conditional rendering

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement