import React, { useEffect, useState, useRef } from "react"; interface Stats { cpu: number; ramUsage: number; ramTotal: number; diskUsage: number; diskTotal: number; network: NetworkStats; uptime: number; } interface NetworkStats { inbound: number; outbound: number; } const StatsComponent = ({ cpu, ramUsage, ramTotal, diskUsage, diskTotal, network, uptime, }: Stats) => { const [inboundSpeed, setInboundSpeed] = useState(0); const [outboundSpeed, setOutboundSpeed] = useState(0); const [uptimeStat, setUptime] = useState(uptime); // useRef to przechowywanie poprzednich wartości bez powodowania ponownego renderowania komponentu const previousInbound = useRef(network.inbound); const previousOutbound = useRef(network.outbound); useEffect(() => { const intervalId = setInterval(() => { const currentInbound = network.inbound; const currentOutbound = network.outbound; const inboundDifference = currentInbound - previousInbound.current; const outboundDifference = currentOutbound - previousOutbound.current; setInboundSpeed(inboundDifference); setOutboundSpeed(outboundDifference); // Aktualizacja poprzednich wartości previousInbound.current = currentInbound; previousOutbound.current = currentOutbound; }, 1000); // Prędkość będzie aktualizowana co 1 sekundę return () => clearInterval(intervalId); // Czyszczenie interwału po odmontowaniu komponentu }, [network.inbound, network.outbound]); // substract current tiimestamp with the timestamp from timestamp variable and convert it to days hours minutes and seconds const formatUptime = (timestamp: number) => { // convert miliseconds to string formatted days hours minutes and seconds const days = Math.floor(timestamp / (1000 * 60 * 60 * 24)); const hours = Math.floor( (timestamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60) ); const minutes = Math.floor((timestamp % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timestamp % (1000 * 60)) / 1000); return `${days}d ${hours}h ${minutes}m`; // return `${days}d ${hours}h ${minutes}m ${seconds}s`; }; return (
Uptime
{formatUptime(uptime)}
CPU
{cpu} %
RAM
{ramUsage} GB
{ramTotal} GB
Storage
{diskUsage} GB
{diskTotal} GB
Network (Inbound)
{Math.round(inboundSpeed / 1024)} kB/s
{Math.round(network.inbound / (1024 * 1024))} MB
Network (Outbound)
{Math.round(outboundSpeed / 1024)} kB/s
{Math.round(network.outbound / (1024 * 1024))} MB
); }; export default StatsComponent;