pretty decent state

This commit is contained in:
counterweight 2025-12-26 18:49:00 +01:00
parent 63a4b0f8a2
commit f6c552cefd
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
10 changed files with 75 additions and 42 deletions

View file

@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from "react";
import { useState, useEffect, useCallback, useRef } from "react";
/**
* Hook for fetching async data with loading and error states.
@ -30,6 +30,16 @@ export function useAsyncData<T>(
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Use ref to store the latest fetcher function to avoid dependency issues
const fetcherRef = useRef(fetcher);
const onErrorRef = useRef(onError);
// Update refs when values change
useEffect(() => {
fetcherRef.current = fetcher;
onErrorRef.current = onError;
}, [fetcher, onError]);
const fetchData = useCallback(async () => {
if (!enabled) return;
@ -37,20 +47,20 @@ export function useAsyncData<T>(
setError(null);
try {
const result = await fetcher();
const result = await fetcherRef.current();
setData(result);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "Failed to load data";
setError(errorMessage);
if (onError) {
onError(err);
if (onErrorRef.current) {
onErrorRef.current(err);
} else {
console.error("Failed to fetch data:", err);
}
} finally {
setIsLoading(false);
}
}, [fetcher, enabled, onError]);
}, [enabled]);
useEffect(() => {
fetchData();