Unlock seamless workflows and faster delivery with our latest releases- get the details

Troubleshooting undefined data in Next.js and Sanity integration

17 replies
Last updated: Jul 6, 2022
Hello,can anyone tell me how could I get the data (during console.log) I am getting undefined in my [slug.js file] this is my code

const myquery = `*[_type == "post"] {
    title,
    _id,
    mainImage,
   body
    }`

export const Post = ({posts, title, image}) => {

    console.log(posts, title, image);
    return (
        <div>
        <h1>Post</h1>
        </div>
    );
};

export const getServersideprops = async () => {
    const result = await client.fetch(myquery)
    return {
        props: {
            title: result.title,
            posts: result.body,
            image: result.mainImage,
        }
    }
}
Jul 6, 2022, 5:25 AM
Your function needs to be
getServerSideProps()
. The capitalization is important.
Jul 6, 2022, 5:56 AM
Ya mybad I did but still undefinedcan I get a code snippet from where I can find how to properly fetch the data from the sanity??
Jul 6, 2022, 5:59 AM
You should use a default export for your component, not a named export. Next.js cannot guess what your component is called. 🙂
Jul 6, 2022, 7:41 AM
Hello ma'am I tried with the export default still my console is showing undefined below is my code snippet
import Head from 'next/head'
import Image from 'next/image'
import {sanityClient, urlFor} from '../sanity';



export default function Home({posts}) {

    console.log(posts);

  return (
    <h1>Welcome</h1>
  );
}


export const getServerSideprops = async () => {
  const query = `*[_type == "post"] {
    title,
    _id,
    mainImage,
    body
    }`
  const posts = await sanityClient.fetch(query)
  return {
    props: {
      posts,
    }
  }
}
 
Jul 6, 2022, 7:56 AM
and this is my sanity.js file
import {
    createClient,
    createPortableTextComponent,
    createImageUrlBuilder,
    createPreviewSubscriptionHook
  } from "next-sanity";

export const config = {
    /**
     * Find your project ID and dataset in `sanity.json` in your studio project.
     * These are considered "public", but you can use environment variables
     * if you want differ between local dev and production.
     *
     * <https://nextjs.org/docs/basic-features/environment-variables>
     **/
    dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || "production",
    projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
    apiVersion: "2021-08-11", // or today's date for latest
    /**
     * Set useCdn to `false` if your application require the freshest possible
     * data always (potentially slightly slower and a bit more expensive).
     * Authenticated request (like preview) will always bypass the CDN
     **/
    useCdn: process.env.NODE_ENV === "production",
  };

  // setup the client for fetching data in the getProps page functions
  export const sanityClient = createClient(config);

  export const urlFor = (source) =>
  createImageUrlBuilder(config).image(source);


// export const useCurrentUser = createCurrentUserHook(config);
Jul 6, 2022, 7:57 AM
Just double checking but: are you reaching the right page in the browser? 🙂
Jul 6, 2022, 7:58 AM
yes I am trying with the home page only
Jul 6, 2022, 7:59 AM
see I am getting the query but in next.js it is undefined
Jul 6, 2022, 8:01 AM
Oh, I know why. You’re querying an array of posts, not a single one — the query in Vision shows that as well. You need to add
[0]
to your query if you want a single post, or you need to treat a collection (with a map or something).
Jul 6, 2022, 8:03 AM
I mean, a good way to check that your query works is to log the result of the actual query before you pass it down to your component. I think it would show you tht it works fine. 🙂
Jul 6, 2022, 8:04 AM
still undefined 🥲
Jul 6, 2022, 8:19 AM
I will define it by maps when I will get some json data but I am not getting anything
Jul 6, 2022, 8:22 AM
If you log
result
right after the definition, it’s undefined?
Jul 6, 2022, 8:22 AM
Like this??
export const getServerSideprops = async () => {
  const query = `*[_type == "post"][0] {
    title,
    _id,
    mainImage,
    body
    }`
  const posts = await sanityClient.fetch(query);
  
  return {
    props: {
      posts,
    },
  }
  console.log({posts});
}
Jul 6, 2022, 8:25 AM
Before the return statement, otherwise it will not fire. 🙂
Jul 6, 2022, 8:53 AM
Also remember that
[0]
in your query means you pick up the first post, so the variable probably shouldn’t be named
posts
. 😉
Jul 6, 2022, 8:54 AM
And as
user A
stated above it is important to have the right kind of capitalisation in your functions:
â›” getServerSideprops()
✅ get*S*erver*S*ide*P*rops()
Jul 6, 2022, 12:21 PM

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?