import Link from 'next/link';
import React from 'react'
const getProducts = async () => {
try {
const res = await fetch("http://localhost:3000/api/product",{
cache: 'no-cache',
});
if (!res.ok) {
throw new Error("Failed to fetch products");
}
return res.json();
} catch (err) {
console.error("Error loading product", err);
}
};
export default function ProductListPage() {
const {products } = getProducts();
return (
<div>
<Link href={"/addProduct"}>
Add Product
</Link>
<div className='overflow-x-auto'>
<table className='table table-zebra'>
{/* head */}
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
{products.map((pro) => (
<tr>
<td>{pro._id}</td>
<td>{pro.name}</td>
<td>{pro.email}</td>
<td>{pro.password}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
```getting this error "app/components/ProductListPage.js (40:22) @ map
⨯ TypeError: Cannot read properties of undefined (reading 'map')
at ProductListPage (./app/components/ProductListPage.js:86:48)
at stringify (<anonymous>)
digest: "1553693874"
38 | </thead>
39 | <tbody>
> 40 | {products.map((pro) => (
| ^
41 | <tr>
42 | <td>{pro._id}</td>
43 | <td>{pro.name}</td>" and when i try ? it shows blank
#Error while fetching
15 messages · Page 1 of 1 (latest)
🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord
🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize
✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)
Please show us the code of your API. Your "products" are undefined.
import Product from "@/app/models/ProductModel";
import { NextResponse } from "next/server";
export async function GET(request){
await connectMongo();
const products = await Product.find();
return NextResponse.json({products},{status: 200});
}
export async function POST(request){
const {name, email, password} = await request.json();
await connectMongo();
await Product.create({name, email, password});
return NextResponse.json({message: 'Product created successfully'}, {status: 201})
}
export async function DELETE(request){
const id = request.nextUrl.searchParams.get("id");
await connectMongo();
await Product.findByIdAndDelete(id);
return NextResponse.json({message: 'Product deleted successfully'}, {status: 200})
}```
@shrewd basin Try this:
const { products } = await getProducts()
import RemoveBtn from "./RemoveBtn";
import Image from "next/image";
const getProducts = async () => {
try {
const res = await fetch("http://localhost:3000/api/products", {
cache: "no-store",
});
if (!res.ok) {
throw new Error("Failed to fetch products");
}
const products = await res.json();
return { products };
} catch (error) {
console.log("Error loading products: ", error);
}
};
export default async function ProductssList() {
const {products} = await getProducts();
return ()
<>
``` its giving me Error: Cannot destructure property 'products' of '(intermediate value)' as it is undefined.
import connectMongoDB from "@/app/libs/connectMongoDB";
import ProductModel from "@/app/models/ProductModels";
import { NextResponse } from "next/server";
export async function GET() {
await connectMongoDB();
const products = await Product.find();
return NextResponse.json({ products });
}
export async function POST(request) {
const { name, image, price, category } = await request.json();
await connectMongoDB();
await ProductModel.create({ name, image, price, category });
return NextResponse.json({ message: "Product Created" }, { status: 201 });
}
export async function DELETE(request) {
const id = request.nextUrl.searchParams.get("id");
await connectMongoDB();
await ProductModel.findByIdAndDelete(id);
return NextResponse.json({ message: "Product deleted" }, { status: 200 });
}
import connectMongoDB from "@/app/libs/connectMongoDB";
import ProductModel from "@/app/models/ProductModels";
import { NextResponse } from "next/server";
export async function GET() {
await connectMongoDB();
const products = await Product.find();
// ----------------------^^^^^^^--------
return NextResponse.json({ products });
}
export async function POST(request) {
const { name, image, price, category } = await request.json();
await connectMongoDB();
await ProductModel.create({ name, image, price, category });
return NextResponse.json({ message: "Product Created" }, { status: 201 });
}
export async function DELETE(request) {
const id = request.nextUrl.searchParams.get("id");
await connectMongoDB();
await ProductModel.findByIdAndDelete(id);
return NextResponse.json({ message: "Product deleted" }, { status: 200 });
}
What is this
route
import mongoose, { Schema } from "mongoose";
{
name: { type: String, required: true },
category: { type: String, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
},
{
timestamps: true,
}
);
const ProductModel =
mongoose.models.Product || mongoose.model("Product", topicSchema);
export default ProductModel; ```
ohh its the schema or the name
I think the Product is undefined.
await Product.find();
ahh it got fixed but not i am getting problem here {products.map(rs => ( "Unhandled Runtime Error
Error: products.map is not a function"
Try to log the products and see what you get.
i finally got the result. i messed up in route 😅