Right now my code is pulling its JSON from a file, I am trying to have it pull the data from an API instead, I have successfully printed the array from the API to the console, however when I try to use the .map function on the data I pulled, I receive an error saying that the variable holding my array is unidentified.
Working code that prints array to console:
import React from 'react';
import { MDBDataTable } from 'mdbreact';
import API_Data from '../myJSON_Data.json';
const DatatablePage = () => {
fetch('https://api')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
const data = {
columns: [
{
label: 'Name',
field: 'name',
sort: 'asc',
width: 150
}
],
rows: API_Data.map(API_Data => {
return {
state: API_Data.name
}
})
};
return (
<div>
<div>
<div>
<div>
<h1>Data from API</h1>
<MDBDataTable
striped
bordered
hover
data={data}
/>
</div>
</div>
</div>
</div>
);
}
export default DatatablePage;
What I have tried:
import React from 'react';
import { MDBDataTable } from 'mdbreact';
const DatatablePage = () => {
var apiData;
fetch('https://api')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
apiData = data;
});
const data = {
columns: [
{
label: 'Name',
field: 'name',
sort: 'asc',
width: 150
}
],
rows: apiData.map(apiData => {
return {
state: apiData.name
}
})
};
return (
<div>
<div>
<div>
<div>
<h1>Data from API</h1>
<MDBDataTable
striped
bordered
hover
data={data}
/>
</div>
</div>
</div>
</div>
);
}
export default DatatablePage;