MarkHenri
MarkHenri

Reputation: 77

NextJs not getting data from sanity

I am new to sanity and I am trying to replicate a tutorial, but when I get the stage of returning data from sanity, it just shows undefined when i console logged the elements I am trying to get from sanity. here is the code for my page.

export default function Home({products,bannerData}) {
  return (
    <div>
    <HeroBanner herobanner={bannerData.lenght && bannerData[0]}/>
    <div className="products-heading">
      <h2>Best Seller Products</h2>
      <p>speaker There are many variations passages</p>
    </div>

    <div className="products-container">
      {products?.map((product) => <Product key={product._id} product={product} />)}
    </div>

    <FooterBanner/>
  </div>
  )
  
};

export async function getStaticProps(){
  const products = await client.fetch('*[_type == "product"]');
  const bannerData = await client.fetch('*[_type == "banner"]');
  return { props: { products, bannerData } };
};

when i run the queries through the vision tab in sanity studio, it returns data there. i have setup the client successfully in nextjs here's my setup;

import imageUrlBuilder from '@sanity/image-url';


export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET // "production"
export const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION // "2023-05-06"
export const token = process.env.SANITY_SECRET_TOKEN

export const client = createClient({projectId, dataset, apiVersion, token, useCdn: true})

const builder = imageUrlBuilder(client);

export const urlFor = (source) => builder.image(source);

I dont really why its returning undefined, I'd appreciate any help!

Upvotes: 2

Views: 997

Answers (2)

Okiemute Gold
Okiemute Gold

Reputation: 548

you don't necessarily need to do that.

Data fetching is now done in a different way.

Reference: Data Fetching. See also, Migrating From Pages to App

Upvotes: 1

MarkHenri
MarkHenri

Reputation: 77

I solved the problem by changing the folder structure to pages, if you are using NextJs, getServerSideProps dont work if your page/index file is in App folder.

Upvotes: 0

Related Questions