This code below is to read data from an api, but it throws this error "TypeError: ecwidData.map is not a function".
Note: I'm a beginner learning js and reactjs currently.
. . .
page imports
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Table } from "semantic-ui-react";
.............
The Function code
export default function Read() {
let [ecwidData, setEcwidData] = useState([]);
useEffect(() => {
axios.get(
'apiurl'
)
.then((response) => {
setEcwidData(response.data);
})
.catch((error) => {
document.write(error);
})
}, [])
return (
<div>
<Table singleLine>
<Table.Header>
<Table.Row>
<Table.HeaderCell>ID</Table.HeaderCell>
<Table.HeaderCell>Category</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
<Table.HeaderCell>URL</Table.HeaderCell>
<Table.HeaderCell>Products count</Table.HeaderCell>
<Table.HeaderCell>Enabled</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{ecwidData.map((data) => {
return (
<Table.Row>
<Table.Cell>{data.id}</Table.Cell>
<Table.Cell>{data.name}</Table.Cell>
<Table.Cell>{data.description}</Table.Cell>
<Table.Cell>{data.url}</Table.Cell>
<Table.Cell>{data.productCount}</Table.Cell>
<Table.Cell>{data.enabled}</Table.Cell>
</Table.Row>
);
})}
</Table.Body>
</Table>
</div>
);
}
...... ...... This is the api response from calling the api in the browser: ...... ......
{
"total": 58,
"count": 58,
"offset": 0,
"limit": 100,
"items": [
{
"id": 127443167,
"parentId": 127443594,
"orderBy": 10,
"name": "Bathroom robe",
"nameTranslated": {
"ar": "Bathroom robe",
"en": "",
"fr": ""
},
"url": "",
"productCount": 0,
"description": "",
"descriptionTranslated": {
"ar": "",
"en": "",
"fr": ""
},
"enabled": true,
"isSampleCategory": false
}
... etc
CodePudding user response:
you should change:
<Table.Body>
{ecwidData.map((data) => { return (
<Table.Row>
<Table.Cell>{data.id}</Table.Cell>
<Table.Cell>{data.name}</Table.Cell>
<Table.Cell>{data.description}</Table.Cell>
<Table.Cell>{data.url}</Table.Cell>
<Table.Cell>{data.productCount}</Table.Cell>
<Table.Cell>{data.enabled}</Table.Cell>
</Table.Row>
); })}
</Table.Body>
to
<Table.Body>
{ecwidData?.items?.map((data) => { return (
<Table.Row>
<Table.Cell>{data.id}</Table.Cell>
<Table.Cell>{data.name}</Table.Cell>
<Table.Cell>{data.description}</Table.Cell>
<Table.Cell>{data.url}</Table.Cell>
<Table.Cell>{data.productCount}</Table.Cell>
<Table.Cell>{data.enabled}</Table.Cell>
</Table.Row>
); })}
</Table.Body>