I've been struggling a bit with this library and javascript. So here is the deal, I want to build a table from data I'm collecting from a Http Get request. I'm ok on getting the data, but I'm not able to work with the Data. It says it is an empty array.
Here is the code:
import React, { useEffect, useState } from "react";
import axios from "axios";
import { DataGrid } from "@material-ui/data-grid";
function ServersTable() {
const [loadingData, setLoadingData] = useState(true);
const [serverData, setServerData] = useState([]);
const [rows, setRows] = useState([]);
const columns = [
{ field: "hostname", headerName: "Hostname", width: 70 },
{ field: "memory", headerName: "Memória", width: 70 },
{ field: "vCpus", headerName: "vCPUs", width: 70 },
{ field: "disk", headerName: "Disco", width: 70 },
{ field: "ip", headerName: "IP", width: 70 },
];
useEffect(() => {
async function getData() {
await axios
.get("http://localhost:3333/servers")
.then((response) => {
setServerData(response.data);
fillRows();
setLoadingData(false);
})
}
if (loadingData) {
getData();
}
}, []);
function fillRows() {
let rowArray = [];
for (let count = 0; count < serverData.length; count++) {
let row;
row = {
id: count,
hostname: serverData[count].hostname,
memory: serverData[count].configuracao.memoryProvisioned + " GB",
vCpus: serverData[count].configuracao.cpuProvisioned + " vCPUs",
disk: serverData[count].configuracao.totalDiskGB + " GB",
ip: serverData[count].ip,
};
rowArray.push(row);
}
setRows(rowArray);
}
return (
<>
{loadingData ? (
<p>Loading Please Wait...</p>
) : (
<DataGrid rows={rows} columns={columns} checkboxSelection />
)}
{console.log("Server Data:")}
{console.log(serverData)}
{console.log("Rows:")}
{console.log(rows)}
</>
);
}
export default ServersTable;
I think I'm struggling in understandig how the async is working and I'm trying to access the data before it is ready. Though I tried everything to make it work and wait for the data to be ready.
Could anyone help me?