File size: 1,729 Bytes
60b2d8c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import { useState, useEffect, useCallback, useRef } from "react";
interface SimulationOptions {
interval?: number;
initialDelay?: number;
enabled?: boolean;
}
/**
* Custom hook for simulating real-time data updates
* @param dataGenerator Function that generates the data
* @param options Configuration options for the simulation
* @returns The current simulated data and loading state
*/
export function useDataSimulation<T>(
dataGenerator: () => T,
options: SimulationOptions = {}
) {
const {
interval = 2000, // Reduced from 5000ms to 2000ms for faster updates
initialDelay = 500, // Reduced from 1000ms to 500ms for faster initial load
enabled = true
} = options;
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const generatorRef = useRef(dataGenerator);
// Update the ref when the generator changes
useEffect(() => {
generatorRef.current = dataGenerator;
}, [dataGenerator]);
const generateData = useCallback(() => {
return generatorRef.current();
}, []);
useEffect(() => {
if (!enabled) {
setLoading(false);
return;
}
// Initial data load with delay to simulate API fetching
const initialTimer = setTimeout(() => {
setData(generateData());
setLoading(false);
}, initialDelay);
// Set up interval for regular data updates
const intervalTimer = setInterval(() => {
setData(generateData());
}, interval);
return () => {
clearTimeout(initialTimer);
clearInterval(intervalTimer);
};
}, [generateData, interval, initialDelay, enabled]);
return { data, loading, refreshData: () => setData(generateData()) };
}
|