I 'm new in react and I want to render my products data that I fetch from api. I'm using the map function to show the data I get from the api on the screen. But the following error appears in the console .There is no problem with the data, I can see that it is drawn from the api as console result, but it does not print on the screen in the form of a table, I think it will probably work if I solve the .map function problem. What can be the problem .Have you ever faced this problem ?
ERRORS
ProductList.js:27 Uncaught TypeError: products.map is not a function
The above error occurred in the <ProductList> component:
My ProductList
import { ProductContext } from '../Contexts/ProductContext';
import React, { useContext } from 'react';
import Product from './Product'
export default function ProductList() {
const { products } = useContext(ProductContext);
return (
<>
<div>
<table className='table table-striped table-hover'>
<thead>
<tr>
<th>Product ID</th>
<th>product is offerable</th>
<th>Product Name</th>
<th>Product Description</th>
<th>Product is sold</th>
<th>Category ID</th>
</tr>
</thead>
<tbody>
<div>
{products.map((product) => (
<tr>
<td>{product.productId}</td>
<td>{String(product.isOfferable)}</td>
<td>{product.productName}</td>
<td>{product.productDescription}</td>
<td>{String(product.isSold)}</td>
<td>{product.categoryName}</td>
</tr>
))}
</div>
</tbody>
</table>
</div>
</>
)
}
MY API DATA FROM POSTMAN
{
"data": [
{
"categoryId": 1,
"productId": 1,
"productName": "Bilgisayar",
"categoryName": "Yazılım",
"colorName": "gri",
"price": 15000,
"brandName": "ASUS",
"isOfferable": false,
"isSold": false
}, // example data. it continues like this
CodePudding user response:
You try to iterate over the the object and not the array inside the object. You have to use products.data.map(...)
. Also I would recommend optional chaining on your products object because you will try to access .data
before products
is fully fetched from the server. Therefore your products
object will be undefined at first and you can't access .data
on it.
{products?.data.map((data) => ...}
CodePudding user response:
Do products.data.map()
instead
you skipped data which is the one containing the array