0
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:...
    }
]
2
  • PostData, where exactly is that from, I think we need some more information/code. Commented Mar 22, 2022 at 18:34
  • Done. You can see that Commented Mar 22, 2022 at 18:35

2 Answers 2

0

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}
Sign up to request clarification or add additional context in comments.

5 Comments

This is generating a syntax errors.
Can you paste the error? Propably your issue is that you return null in render. Wrap this answer in a div or fragment and it should work allright
./pages/blog/[postslug].js Error: error: Expression expected | 2795 | { currentPost && currentPost.content} | ^^ error: Expected ',', got '}' | 2795 | { currentPost && currentPost.content} | ^ Caused by: 0: failed to process js file 1: Syntax Error
Now working fine when enclosed your syntax in fragments
Perfect, if this helps you please mark this as an answer!
0

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.

1 Comment

Error: Post(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.