Home > Software design >  how to destructure property if possibly undefined?
how to destructure property if possibly undefined?

Time:10-22

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

CodePudding user response:

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
...

CodePudding user response:

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

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

CodePudding user response:

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 ?? {};
// −−−−−−−−−^^^^^^^^^^^^^^−−−−−−^^^^^−−−−−−−−−−−−−−−^^^^^^
  • Related