Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to destructure property if possibly undefined?

I’m getting stuck on this TS error created at build time. Does anyone has any suggestions?

TypeError: Cannot destructure property ‘site’ of ‘(intermediate value)’ as it is undefined.

export default function Project({
  data,
  preview,
}: {
  data: any
  preview: any
}) {
  const { site, page } = data?.post

  return (
    <Layout site={site} page={page}>
      // Stuff
    </Layout>
  )
}

export async function getStaticProps({ params, preview = false }) {
  const { post, morePosts } = await getClient(preview).fetch(projectQuery, {
    slug: params.slug,
  })

  return {
    props: {
      preview,
      data: {
        post,
        morePosts: overlayDrafts(morePosts),
      },
    },
  }
}

export async function getStaticPaths() {
  const paths = await sanityClient.fetch(projectSlugsQuery)
  return {
    paths: paths.map((slug) => ({ params: { slug } })),
    fallback: true,
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t destructure it

Better to have an early return (in my opinion), and then continue as normal

if (!data) {
  return null
}

const { site, page } = data.post;

// Continue on
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading