See Sanity in action 👀 Join us for a live product demo + Q&A →

Troubleshooting undefined data when querying a new document type in a Next.js app with Sanity.io

40 replies
Last updated: Feb 10, 2023
Hey everyone! I've created a new document type called "Global"... I'm trying to query the data but for some reason I'm getting undefined. And strangely, I can seethe data in the terminal, but not the console when trying to log.....
Feb 10, 2023, 7:15 PM
Can you share more of the code around this?
Feb 10, 2023, 7:59 PM
Sure!
Feb 10, 2023, 8:24 PM
I have a schema called "global.ts that is being queried here:
// Global Settings
export const globalSettingsQuery = groq`
*[_type == 'global'][0]
`
Feb 10, 2023, 8:25 PM
That is in
sanity.queries.ts
Feb 10, 2023, 8:26 PM
I'm exporting that type interface like so:


export interface GlobalSettings extends SanityBody {
  _type?: 'global'
  contactInformation?: {
    address?: string
    email?: string
    phoneNumber?: number
  }
  education?: {
    college?: string
    collegeLocation?: string
    dateEnded?: Date
    dateStarted?: Date
    degree?: string
  }
  homepageContent?: {
    heroImage: Image
  }
  personalInformation?: {
    bio?: string
    bioTitle?: string
    name?: string
    profilePic?: Image
    role?: string
  }
  socialMedia?: {
    social?: Social[]
  }
}
Feb 10, 2023, 8:26 PM
Inside
sanity.client.ts
I am calling the query:


export async function getGlobalSettings(): Promise<GlobalSettings | {}> {
  if (client) {
    return (await client.fetch(globalSettingsQuery)) || {}
  }
  return {}
}
Feb 10, 2023, 8:27 PM
So I'm trying to grab this data, and be able to use in my own component that I'm making.
Feb 10, 2023, 8:28 PM
getGlobalSettings function is called in the
index.tsx
file:

const [globalSettings, settings, posts = []] = await Promise.all([
    getGlobalSettings(),
    getSettings(),
    getAllPosts(),
  ])
Feb 10, 2023, 8:30 PM
So my thought pattern was to copy all the same functionality for the "settings" which worked out of the box. I've added additional schema work, and I want to query it in the same manner, but for some reason, "settings" has data, but "globalSettings" is undefined (and I am 100% sure there is data).
Feb 10, 2023, 8:31 PM
This is the first connection I have made to my own custom document type. Once I make this connection and understand how its working, I'm sure I can apply the same logic to my other data I'll need to retrieve.
Feb 10, 2023, 8:33 PM
Stepping away for 10 min to get my daughter, but I will be back! Any help here would be 100% appreciated...
Feb 10, 2023, 8:52 PM
I’m wrapping up a meeting but will jump back in here as soon as I’m able to.
Feb 10, 2023, 8:53 PM
For reference, I am using this nextjs starter: https://www.sanity.io/blog/nextjs-authoring-experience-with-sanity
Feb 10, 2023, 9:34 PM
Hmm, that code all looks ok. Is it possible that you’re not returning the data from this line:
const [globalSettings, settings, posts = []] = await Promise.all([
    getGlobalSettings(),
    getSettings(),
    getAllPosts(),
  ])
Feb 10, 2023, 9:46 PM
Thats what I'm not sure of. I was thinking that I could copy the logic of the "settings" type to connect to my own document type, and as far as I can see I have all the parts.
Feb 10, 2023, 9:49 PM
When I console log "settings" and my "globalSettings" at the same place, only settings returns results. "globalSettings" is undefined
Feb 10, 2023, 9:52 PM
Can you share your entire
getStaticProps
function?
Feb 10, 2023, 9:55 PM
in the index page that is!
Feb 10, 2023, 9:55 PM
export const getStaticProps: GetStaticProps<
  PageProps,
  Query,
  PreviewData
> = async (ctx) => {
  const { preview = false, previewData = {} } = ctx

  const [globalSettings, settings, posts = []] = await Promise.all([
    getGlobalSettings(),
    getSettings(),
    getAllPosts(),
  ])

  console.log('Another Test: ', globalSettings.socialMedia.social)

  return {
    props: {
      posts,
      settings,
      globalSettings,
      preview,
      token: previewData.token ?? null,
    },
  }
}
Feb 10, 2023, 9:56 PM
That looks correct, too! Can you share the entirety of your index page?
Feb 10, 2023, 10:03 PM
Yep!
Feb 10, 2023, 10:15 PM
import { PreviewSuspense } from '@sanity/preview-kit'
import IndexPage from 'components/IndexPage'
import { getAllPosts, getSettings, getGlobalSettings } from 'lib/sanity.client'
import { Post, Settings, GlobalSettings } from 'lib/sanity.queries'
import { GetStaticProps } from 'next'
import { lazy } from 'react'

const PreviewIndexPage = lazy(() => import('components/PreviewIndexPage'))

interface PageProps {
  posts: Post[]
  settings: Settings
  social: GlobalSettings['socialMedia']
  globalSettings: GlobalSettings
  preview: boolean
  token: string | null
}

interface Query {
  [key: string]: string
}

interface PreviewData {
  token?: string
}

export default function Page({
  posts,
  settings,
  globalSettings,
  social,
  preview,
  token,
}: PageProps) {
  console.log('Test: ', social)
  if (preview) {
    return (
      <PreviewSuspense
        fallback={
          <IndexPage
            loading
            preview
            posts={posts}
            settings={settings}
            social={social?.social}
          />
        }
      >
        <PreviewIndexPage token={token} />
      </PreviewSuspense>
    )
  }

  return <IndexPage posts={posts} settings={settings} social={social?.social} />
}

export const getStaticProps: GetStaticProps<
  PageProps,
  Query,
  PreviewData
> = async (ctx) => {
  const { preview = false, previewData = {} } = ctx

  const [globalSettings, settings, posts = []] = await Promise.all([
    getGlobalSettings(),
    getSettings(),
    getAllPosts(),
  ])

  console.log('Another Test: ', globalSettings.socialMedia.social)

  return {
    props: {
      posts,
      settings,
      globalSettings,
      preview,
      token: previewData.token ?? null,
    },
  }
}
Feb 10, 2023, 10:15 PM
Now, there is likely some issues here. I've been making some edits trying different things out. 🥴
Feb 10, 2023, 10:15 PM
There's some things going on with
GlobalSettings["socialMedia"]
that Im not so sure about...
Feb 10, 2023, 10:17 PM
Oh, I think I see it now! Your
Test
console log is logging
social
, which you’re destructuring in your
props
. However, your
getStaticProps
isn’t returning
social
. Social is actually on
globalSettings.socialMedia.social
.
Feb 10, 2023, 10:19 PM
so I can just pass
globalSettings
, and get rid of
social
, right?
Feb 10, 2023, 10:24 PM
and just target it with the dot notation?
Feb 10, 2023, 10:24 PM
Yessss... haha, you're awesome!
Feb 10, 2023, 10:25 PM
I think the Sanity folk around here need to share a crypto address for tips....
Feb 10, 2023, 10:26 PM
Oh man that was a satisfying one to figure out!
Feb 10, 2023, 10:30 PM
Tell me about it... I've been sitting here banging my head around for hours. lol.... well, I kept coming back to it.
Feb 10, 2023, 10:32 PM
Now this makes sense for me. I can connect the rest of my document types up. 🙂
Feb 10, 2023, 10:32 PM
Everything else will be easy now!
Feb 10, 2023, 10:33 PM
I've spent a lot of time customizing the studio, so I'm excited to get the frontend parts hooked up.
Feb 10, 2023, 10:33 PM
This is what its lookin like:
Feb 10, 2023, 10:33 PM
Very nice! Love the theme.
Feb 10, 2023, 10:34 PM
Thanks!
Feb 10, 2023, 10:34 PM
Last question.... do you know what this error means on getStaticProps?
Feb 10, 2023, 10:55 PM
Hmm, that looks like a type error from Typescript, which I haven’t taken the dive into yet. I don’t think I can be more helpful than that!
Feb 10, 2023, 10:57 PM
Okay thanks!
Feb 10, 2023, 11:03 PM

Sanity.io – build remarkable experiences at scale

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

Categorized in