👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Error in NextJS getStaticProps when destructuring property 'currentPost' as it is null.

8 replies
Last updated: Dec 15, 2021
Has anyone gotten
error - pages/[slug].tsx (171:10) @ getStaticProps
TypeError: Cannot destructure property 'currentPost' of '(intermediate value)' as it is null.
  169 |   })
  170 |
> 171 |   const { currentPost, previousPost, nextPost } = await getClient().fetch(
      |          ^
  172 |     postsTest,
  173 |     {
  174 |       slug: params?.slug,
using NextJS the call in my
getStaticProps
looks like
const { currentPost, previousPost, nextPost } = await getClient().fetch(
    postsTest,
    {
      slug: params?.slug,
    }
  )
and that
postsTest
query looks like
export const postsTest = groq`
*[_type == "post" && slug.current == $slug]{
  "currentPost": {
    ${postFields}
  },
  "previousPost": *[_type == "post" && ^.publishedAt > publishedAt]|order(publishedAt desc)[0]{title,slug},
  "nextPost": *[_type == "post" && ^.publishedAt < publishedAt]|order(publishedAt asc)[0]{title,slug}
}|order(publishedAt)[0]
`

Dec 15, 2021, 4:53 AM
It’s because the filters return
null
 on no hits. So you either need to coalesce them into an empty object, or deal with the
null
 in JS land
*[_type == "post"]{
  title,publishedAt,
  "previous": 
  coalesce(*[_type == "post" && ^.publishedAt > publishedAt && false]|order(publishedAt desc)[0]{title,publishedAt}, {}),
  "next": 
coalesce(*[_type == "post" && ^.publishedAt < publishedAt]|order(publishedAt asc)[0]{title,publishedAt}, {})
}|order(publishedAt)
Dec 15, 2021, 5:05 AM
But it shouldn't be hitting null in the cases I am running into this issue
Dec 15, 2021, 5:07 AM
Can it be because it’s the last or first post?
Dec 15, 2021, 5:08 AM
Nope,
<http://localhost:3000/2021-fcs-playoffs-semifinal-schedule-is-set>
is definitely not the first article nor the last. It seems like when I navigate to an article then navigate back it causes the issue 🤔
Dec 15, 2021, 5:14 AM
It is like the API isn't even responding... As I am now getting
undefined is not an object (evaluating 'currentPost.title')
Dec 15, 2021, 5:15 AM
Ooo I have some old service worker stuff apparently...
Dec 15, 2021, 5:16 AM
Just noticed the source is "Service Worker" 😬
Dec 15, 2021, 5:17 AM
Yup that is what was causing it... Just verified in incognito and removed cache and what not for localhost
Dec 15, 2021, 5:24 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?