Home > Enterprise >  Server Error TypeError: Cannot read properties of undefined (reading 'content')
Server Error TypeError: Cannot read properties of undefined (reading 'content')

Time:03-23

const Post = () => {
    const router = useRouter();
    const slug = router.query.postslug;
    const currentPost = PostData.find((post) => post.slug === slug);

    return (

        currentPost.content

    )
}

export default Post;

Server Error TypeError: Cannot read properties of undefined (reading 'content')

Below is the array of objects

const PostData = [
    {
        id:1,
        slug:...,
        content:...
    }
]

CodePudding user response:

The problem is that content is undefined in context of currentPost. Its undefined because PostData doesnt match the slug.

a quick guard should help the solution

{ currentPost &&  currentPost.content}

CodePudding user response:

I recommend preparing for it not finding anything like this:

currentPost?.content

If you believe this shouldn't give an error ever, as you haven't said this, feel free to return with a comment/edit describing your problem a bit more.

  • Related