Fixed some issues with gpu info refreshing
This commit is contained in:
@@ -3,35 +3,52 @@
|
||||
import { GPUApiResponse, GpuInfo } from '@/types';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export default function useGPUInfo(gpuIds: null | number[] = null) {
|
||||
export default function useGPUInfo(gpuIds: null | number[] = null, reloadInterval: null | number = null) {
|
||||
const [gpuList, setGpuList] = useState<GpuInfo[]>([]);
|
||||
const [isGPUInfoLoaded, setIsLoaded] = useState(false);
|
||||
useEffect(() => {
|
||||
const fetchGpuInfo = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/gpu');
|
||||
const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
const fetchGpuInfo = async () => {
|
||||
setStatus('loading');
|
||||
try {
|
||||
const response = await fetch('/api/gpu');
|
||||
|
||||
const data: GPUApiResponse = await response.json();
|
||||
let gpus = data.gpus.sort((a, b) => a.index - b.index);
|
||||
if (gpuIds) {
|
||||
gpus = gpus.filter(gpu => gpuIds.includes(gpu.index));
|
||||
}
|
||||
|
||||
setGpuList(gpus);
|
||||
} catch (err) {
|
||||
console.log(`Failed to fetch GPU data: ${err instanceof Error ? err.message : String(err)}`);
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
};
|
||||
|
||||
const data: GPUApiResponse = await response.json();
|
||||
let gpus = data.gpus.sort((a, b) => a.index - b.index);
|
||||
if (gpuIds) {
|
||||
gpus = gpus.filter(gpu => gpuIds.includes(gpu.index));
|
||||
}
|
||||
|
||||
setGpuList(gpus);
|
||||
setStatus('success');
|
||||
} catch (err) {
|
||||
console.error(`Failed to fetch GPU data: ${err instanceof Error ? err.message : String(err)}`);
|
||||
setStatus('error');
|
||||
} finally {
|
||||
setIsLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Fetch immediately on component mount
|
||||
fetchGpuInfo();
|
||||
}, []);
|
||||
|
||||
return { gpuList, setGpuList, isGPUInfoLoaded };
|
||||
}
|
||||
// Set up interval if specified
|
||||
if (reloadInterval) {
|
||||
const interval = setInterval(() => {
|
||||
fetchGpuInfo();
|
||||
}, reloadInterval);
|
||||
|
||||
// Cleanup interval on unmount
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}
|
||||
}, [gpuIds, reloadInterval]); // Added dependencies
|
||||
|
||||
return { gpuList, setGpuList, isGPUInfoLoaded, status, refreshGpuInfo: fetchGpuInfo };
|
||||
}
|
||||
Reference in New Issue
Block a user