Next.js: Cannot read property of undefined

Next.js: Cannot read property of undefined

I had a bug in my Next.js app, in which the props passed to my component unexpectedly was undefined. Duckduckgo’ing the issue didn’t result in any resolution, as my particular mistake was a self introduced bug. Just in case others makes the same mistake as I did, here’s a quick write-up.

Consider this /pages/blog.tsx file:

function Blog({ props }) {

    const posts = props.posts

    return (
        <ul>
            {posts.map((post) => (
                <li>{post.title}</li>
            ))}
        </ul>
    )
}

export async function getStaticProps() {

    const posts = [
        { title: "My first blog post"},
        { title: "My second blog post" }
    ]

    return {
        props: {
            posts,
        },
    }
}

export default Blog</code>

When executing the above code, I got this type of error message: “TypeError: Cannot read property ‘posts’ of undefined“. Many Next.js developers may have spotted the bug already, but as a starting Next.js developer I had to review my own code a few times before I identified the bug – I had my Blog component looking for { props }, while the correct parameter is { posts }. This is a working version of the above component:

function Blog({ posts }) {
    
    return (
        <ul>
            {posts.map((post) => (
                <li>{post.title}</li>
            ))}
        </ul>
    )
}

export async function getStaticProps() {

    const posts = [
        { title: "My first blog post"},
        { title: "My second blog post" }
    ]

    return {
        props: {
            posts,
        },
    }
}

export default Blog

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: