I'm trying to come up with a basic dashboard that would display the results of SQL counts inside card elements using React and upon much frustration, I was able to render the component using this code.
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Card, Col, Row } from 'antd';
import "../App.css";
function Dashboard() {
const [cuentaClientes, setcuentaClientes] = useState([]);
const [cuentaVehiculos, setcuentaVehiculos] = useState([]);
useEffect(() => {
axios.get("http://localhost:3002/api/clientes/contar").then((data) => {
setcuentaClientes(data.data);
});
axios.get("http://localhost:3002/api/vehiculos/contar").then((data) => {
setcuentaVehiculos(data.data);
});
}, []);
const yyy = cuentaVehiculos.map((vehiculo) => {
return {
key: vehiculo.total,
total: vehiculo.total,
};
});
const xxx = cuentaClientes.map((cliente) => {
return {
key: cliente.cantidad,
cantidad: cliente.cantidad,
};
});
return (
<div>
<Row gutter={[16, 16]}>
<Col span={8}>
<Card title="Clientes" bordered={false}>
<p>{xxx[0].cantidad}</p>
</Card>
</Col>
<Col span={8}>
<Card title="Vehiculos" bordered={false}>
<p>{yyy[0].total}</p>
</Card>
</Col>
</Row>
</div>
);
}
export default Dashboard;
However, whenever I refresh the page for whatever reason, the browser throws an error saying variables xxx and yyy are undefined. The error only goes away when I remove their references, like this:
from <p>{xxx[0].cantidad}</p>
to <p></p>
Then, in order to see the count again, I just add the references again.
How can I prevent this from happening?
Thank you all in advance.
CodePudding user response:
return (
<div>
<Row gutter={[16, 16]}>
<Col span={8}>
<Card title="Clientes" bordered={false}>
<p>{xxx?.[0]?.cantidad ?? ''}</p>
</Card>
</Col>
<Col span={8}>
<Card title="Vehiculos" bordered={false}>
<p>{yyy?.[0]?.total ?? ''}</p>
</Card>
</Col>
</Row>
</div>
);
xxx?.[0]?.cantidad ?? ''
Initially it will return an empty string or you can write xxx?.[0]?.cantidad ?? 'Loading...'
. Once it is loaded it will show the required data.