Next.js Discord

Discord Forum

need help with tutorials on how to fetch data from mongodb

Unanswered
Pembroke Welsh Corgi posted this in #help-forum
Open in Discord
Pembroke Welsh CorgiOP
Hello, Some good recommendations of tutorials on how to fetch data from mongodb in next js

8 Replies

@Pembroke Welsh Corgi Hello, Some good recommendations of tutorials on how to fetch data from mongodb in next js
you can use this guide to see how it works ([click me](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching)). In general its like this:
export default async function Page() {
  const data = await fetch('https://api.vercel.app/blog') // or your own fetching function. Or your SDK. Or ...
  const posts = await data.json()
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}
@Pembroke Welsh Corgi solved?
@B33fb0n3 <@902217265964015668> solved?
Pembroke Welsh CorgiOP
yeah
but now i have another issue. I can fetch all products from the database, but when I'm trying to access products/[slug]/page.tsx i get error "TypeError: Cannot read properties of undefined (reading '0')"
this is products/[slug]/page.tsx
export interface ProductType {
  id: string;
  name: string;
  price: number;
  rating: number;
  slug: string;
  description: string;
  product:string;
  images: {
    id: string;
    file: {
      url: string;
      metadata: string;
    };
  }[];
}

export interface ProductProps {
  product: ProductType 

}

async function fetchProductBySlug(): Promise<ProductType> { 
  const response = await fetch(`http://localhost:3000/api/products`);

  if (!response.ok) {
    throw new Error('Failed to fetch product');
  }

  return response.json();
}
0
const Page = async ({ }: { params: { slug: string } }) => {
  const product = await fetchProductBySlug();

  return ( 
    <main>
      <Product product={product} />
    </main>
  );
};

export default Page;
and this is /components/Product.tsx where I get the error
const [selectedImage, setSelectedImage] = useState(product.images[0])

I guess is an issue with product.images[0]
Pembroke Welsh CorgiOP
Yeah, i figured after I wrote the post! I solved it!