Download src/hooks/useDataSimulation.ts from p3rc03/M3S: direct link, hf CLI and curl.
- Browser
- Download file 1.73 kB
-
https://huggingface.co/spaces/p3rc03/M3S/resolve/main/src/hooks/useDataSimulation.ts
- Command line
-
hf download hf://spaces/p3rc03/M3S/src/hooks/useDataSimulation.ts
-
curl -L -o useDataSimulation.ts https://huggingface.co/spaces/p3rc03/M3S/resolve/main/src/hooks/useDataSimulation.ts
1.73 kB
| 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()) }; | |
| } | |