i am using next js 13.4.19. i have made a GET api and trying to access the data available at mongodb database. but when i try to map the data it shows me error Error: data?.map is not a function. This is my product Schema
import mongoose from "mongoose";
const productSchema = new mongoose.Schema({
name: String,
price: Number,
category: String,
});
export const Product =
mongoose.models.products || mongoose.model("products", productSchema);
here is my GET API
import { dbStr } from "@/database/connection";
import { Product } from "@/model/product/product";
import mongoose from "mongoose";
import { NextResponse } from "next/server";
export async function GET() {
let data = [];
try {
await mongoose.connect(dbStr);
data = await Product.find();
} catch (error) {
console.log(error);
}
return NextResponse.json({ data }, { success: true });
}
i have tested the api its working fine and showing the data as follows
{
"data": [
{
"_id": "64fd823b07208cd28468b70e",
"name": "samsung",
"price": 1200,
"category": "mobile",
"__v": 0
},
{
"_id": "64fe1aa2e801f1d8af66b362",
"name": "abc",
"price": 2,
"category": "abc",
"__v": 0
},
{
"_id": "64fe1ae7e801f1d8af66b366",
"name": "shehz",
"price": 200,
"category": "gg",
"__v": 0
},
]
}
but when i try to to get the data from above given api i got error
import React from "react";
async function getData() {
const res = await fetch("http://localhost:3000/api/products");
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error("Failed to fetch data");
}
return res.json();
}
const GetProducts = async () => {
const data = await getData();
return (
<div>
<h1>Get All Products Data</h1>
<table>
<thead>
<tr>
<td>name</td>
<td>price</td>
<td>category</td>
</tr>
</thead>
<tbody>
{data?.map((item) => {
return (
<tr key={item._id}>
<td>{item.name}</td>
<td>{item.price}</td>
<td>{item.category}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default GetProducts;
at the server side i am facing the issue
error TypeError: data?.map is not a function
at GetProducts (./src/component/GetProducts.js:69:41)
26 | </thead>
27 | <tbody>
> 28 | {data?.map((item) => {
| ^
29 | return (
30 | <tr key={item._id}>
31 | <td>{item.name}</td>
Can you try this? data has a key data inside it that you need to access to map over it.