Error calling si.currentLoad(); inside setInterval

48 Views Asked by At

The behaviour is weird, i get as output: Número de Núcleos: 8 Núcleo1: 2.17% Núcleo2: 8.02% Núcleo3: 8.45% Núcleo4: 5.02% Núcleo5: 4.66% Núcleo6: 4.24% Núcleo7: 7.76% Núcleo8: 1.70%

But when the setInterval calls it again: Número de Núcleos: 8 Núcleo1: NaN% Núcleo2: NaN% Núcleo3: NaN% Núcleo4: NaN% Núcleo5: NaN% Núcleo6: NaN% Núcleo7: NaN% Núcleo8: NaN%

If i call it multiple times in a row using console.log outside the component works fine.

import React, { useState, useEffect } from 'react';
import { render, Text } from 'ink';
import si from 'systeminformation';

async function getCPUPercentages() {
  try {
    const cpuData = await si.currentLoad();
    const numCores = cpuData.cpus.length;

    // console.log(JSON.stringify(cpuData, null, 2));

    const corePercentages = cpuData.cpus.map((core) => {
      return core.load.toFixed(2);
    });

    const resultString = [`Número de Núcleos: ${numCores}`];

    corePercentages.forEach((percentage, index) => {
      const coreNumber = index + 1;
      resultString.push(`Núcleo${coreNumber}: ${percentage}%`);
    });

    return resultString.join('\n');
  } catch (err) {
    console.error('Error al obtener información de CPU:', err);
    return 'Error al obtener información de CPU.';
  }
}

const Counter = () => {
  const [counter, setCounter] = useState('');

  useEffect(() => {
    const fetchCPUPercentages = async () => {
      try {
        const percentages = await getCPUPercentages();
        setCounter(percentages);
      } catch (error) {
        console.error('Error al obtener porcentajes de CPU:', error);
        setCounter('Error al obtener porcentajes de CPU.');
      }
    };

    const timer = setInterval(() => {
      fetchCPUPercentages();
    }, 2000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return <Text color="green">{counter}</Text>;
};

render(<Counter />);

Tho run this code you need to: npm init

npm install react, ink, systeminformation

add the "type": "module", into the package.json

use next tsconfig.json:

{
"compilerOptions": {
                "moduleResolution": "node16",
                "module": "node16",
                "outDir": "build",
                "sourceMap": true,
                "jsx": "react",
                "allowJs": true
        },
        "include": ["src"],
        "ts-node": {
                "transpileOnly": true,
                "files": true,
                "experimentalResolver": true,
                "experimentalSpecifierResolution": "node"
        }
}

compile the ./src/index.js into the runnable ./build/index.js usinf the command npx tsc If you don't have typescript compiler you can install it. npm i -g typescript

0

There are 0 best solutions below