how to destructure property if possibly undefined?

how to destructure property if possibly undefined?

Problem Description:

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,
  }
}

Solution – 1

data?.post will return undefined if post does not exist, so you have to add a fallback object.

const { site, page } = data?.post || {};

Solution – 2

You can’t destructure without having a source to destructure from, but you can use a default via nullish coalescing:

const { site, page } = data?.post ?? {};
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^

Your current data is of type any, so that should work, but if it had a proper type you might want to provide default values for site and page. For instance if data had the type {post: {site: string; page: number; }; }:

const { site = "something", page = 42 } = data?.post ?? {};
// −−−−−−−−−^^^^^^^^^^^^^^−−−−−−^^^^^−−−−−−−−−−−−−−−^^^^^^

Solution – 3

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
...
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject