'React Axios to return data from MYSql
I have this React.JS code to return a list of products. The console.log returns the right set of data. But when displaying the data, the display code returns the Error:
TypeError: products.map is not a function
The code:
import { Route, Switch, useHistory } from 'react-router-dom';
import { CCol, CRow } from "@coreui/react";
import { useState, useEffect } from 'react';
import api from '../../../axrootpath';
function Products() {
const [products, setProducts] = useState([])
useEffect(() => {
const fetchProducts = async () => {
try {
const response = await api.get('api/products');
setProducts(response.data);
**{/*The following line returns the correct data set */}**
console.log(products);
} catch (err) {
if (err.response) {
// Not in the 200 response range
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else {
console.log(`Error: ${err.message}`);
}
}
}
fetchProducts();
}, [])
return (
<div className="animated fadeIn">
<CRow>
<CCol xs={12}>
<table
id="productListTable"
className="table table-striped table-bproductd"
>
<thead>
<tr>
<th>Product Number</th>
<th>Description</th>
<th>Group</th>
<th>Account Number</th>
<th>Product Type</th>
<th>Unit</th>
<th>Packing Type</th>
</tr>
</thead>
<tbody>{products.map( (products) => {
return (
<tr key={products.prt_no}>
<td>{products.DSCRPT}</td>
<td>{products.ITEM_GROUP}</td>
<td>{products.ACC_GROUP}</td>
<td>{products.MATERIAL}</td>
<td>{products.UI}</td>
<td>{products.PU}</td>
</tr>
);
})}</tbody>
</table>
</CCol>
</CRow>
</div>
);
}
export default Products;
The console.log(products) looks like that: Object products: Array(1318) [0 … 99] 0: {PRT_NO: 'CU-STND1BLK', DSCRPT: 'Cu Stnd. PVC 1mm - Black', ITEM_GROUP: 'WIRES', ACC_GROUP: 'WIRES', MATERIAL: 'Y', …} 1: {PRT_NO: 'CU-STND1BLU', DSCRPT: 'Cu Stnd. PVC 1mm - Blue', ITEM_GROUP: 'WIRES', ACC_GROUP: 'WIRES', MATERIAL: 'Y', …} 2: {PRT_NO: 'CU-STND1RED', DSCRPT: 'Cu Stnd. PVC 1mm - Red', ITEM_GROUP: 'WIRES', ACC_GROUP: 'WIRES', MATERIAL: 'Y', …} 3: {PRT_NO: 'CU-STND1YLW', DSCRPT: 'Cu Stnd. PVC 1mm - Ylw.', ITEM_GROUP: 'WIRES', ACC_GROUP: 'WIRES', MATERIAL: 'Y', …}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
