Search code examples
reactjstypescriptnext.jssanity

How can I fetch data from Sanity


I tried to create a schema and fetch data from sanity. but console log shows undefined. what am I doing wrong here? I probably failed at creating the schema but I'm not sure.

Testimonials.tsx


interface Props {
    testimonial: [Testimonial]
}

const Testimonials = ({ testimonial } : Props) => {
    console.log(testimonial)
 return ( 
<div className="testimonials_info">
                    <h5>TESTIMONIALS</h5>
</div>
)
}

export getserverside props

export const getServerSideProps = async () => {
  const query = `*[ _type == "testimonial"] {
        title,
        slug,
        description,
    }`;

  const testimonials = await sanityClient.fetch(query)

  if (!testimonials.length) {
    return {
      props: {
        testimonials: [],
      },
    }
  } else {
    return {
      props: {
        testimonials,
      },
    }
  }
}

testimonials.js (schema). I built it very random I'm not sure did I pass it right to the getserversideprops .

export default {
  name: "testimonials",
  title: "Testimonials",
  type: "document",
  fields: [
    {
      name: "title",
      title: "Title",
      type: "string",
    },
    {
      name: "publishedAt",
      title: "Published at",
      type: "datetime",
    },
    {
      name: "body",
      title: "Text",
      type: "blockContent",
    },
  ],

  preview: {
    select: {
      title: "testimonials",
    },
  },
};

typing.d.tsx

export interface Testimonial {
    _id: string;
    _createdAt: string;
    title: string;
    description: string;
    author: string;
    slug: {
        current: string;
    };
    body: [object];
}

Solution

  • It looks like your query is looking for 'testimonial' types but the name of your schema is 'testimonials'. Changing it to the following should work:

    const query = `*[ _type == "testimonials"] {
            title,
            slug,
            description,
        }`;