Error while fetching
Answered
Otterhound posted this in #help-forum
OtterhoundOP
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
13 Replies
Please show us the code of your API. Your "products" are undefined.
OtterhoundOP
import connectMongo from "@/app/libs/connectMongo";
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})
}
@Otterhound Try this:
const { products } = await getProducts()
@Hong <@817403407181545482> Try this:
tsx
const { products } = await getProducts()
OtterhoundOP
import Link from "next/link";
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
OtterhoundOP
route
I mean in the code, the
Product
I commented it
OtterhoundOP
import mongoose, { Schema } from "mongoose";
ohh its the schema or the name
const topicSchema = new Schema(
{
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();
Answer
OtterhoundOP
ahh it got fixed but not i am getting problem here {products.map(rs => ( "Unhandled Runtime Error
Error: products.map is not a function"
Error: products.map is not a function"
Try to log the
products
and see what you get.OtterhoundOP
i finally got the result. i messed up in route 😅