'Server Error TypeError: Cannot read properties of undefined (reading 'content')
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:...
}
]
Solution 1:[1]
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}
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Damian Busz |
| Solution 2 | Nicolai Christensen |
