import { useState, useEffect, useCallback, useRef } from 'react'; import { retryPromise…
- User
import { useState, useEffect, useCallback, useRef } from 'react';
import { retryPromise } from '/utils/retryPromise'; import { FontGroup } from '/Steps/Fonts/data/fontData';
interface Props { fontData: Array; loadFont: (fontFamily: string) => Promise; }
interface Output { isLoading: boolean; hasError: boolean; }
function useLoadFonts({ fontData, loadFont }: Props): Output { const [isLoading, setIsLoading] = useState(true); const [hasError, setHasError] = useState(false); const loaded = useRef(new Set()); console.log("emi's fat ass", isLoading);
const nir: typeof loadFont = useCallback( async (x: string) => { console.time(x); await loadFont(x); console.timeEnd(x); }, [loadFont] );
useEffect(() => { // First, collect all font family tuples (header, body) const fontTuples = fontData.flatMap(({ fonts }) => fonts.map((fontPack) => [fontPack.headerFontFamily, fontPack.bodyFontFamily]) );
const fonts = fontTuples.flatMap((fontTuple2) => fontTuple2);
const toLoad = fonts.filter((f) => !loaded.current.has(f));
if (!toLoad.length) { return; }
toLoad.forEach((f) => loaded.current.add(f)); console.log(fontData);
// Then, create promises for each font family in the tuples const promises = fontTuples.flatMap(([headerFont, bodyFont]) => [ retryPromise(() => nir(headerFont)).catch(() => setHasError(true)), retryPromise(() => nir(bodyFont)).catch(() => setHasError(true)), ]);
Promise.allSettled(promises).then(() => setIsLoading(!fonts.some((f) => loaded.current.has(f))) );
IGNORE_WHEN_COPYING_START Use code with caution. IGNORE_WHEN_COPYING_END
}, [fontData, nir]);
return { isLoading, hasError }; }
export default useLoadFonts;
ignoring the timing / debug code is there a nicer way to handle the fact that fonts can change, we need an accurate loading / error state, and we don't want duplicate requests, if possible, while keeping the code minimal, clean
// Requirments: // - Loading state stays true until all fonts are really loaded (not empty, empty = loading) // - When fonts change, new fonts are loaded & is loading is updated // - Fonts that are already fetched are not fetched again
Assistant
Here's a refactored version of your code that maintains the same functionality while improving readability and minimizing duplicate requests:
import { useState, useEffect, useCallback } from 'react'; import { retryPromise } from '/utils/retryPromise'; import { FontGroup } from '/Steps/Fonts/data/fontData'; interface Props { fontData: Array<FontGroup>; loadFont: (fontFamily: string) => Promise<void>; } interface Output { isLoading: boolean; hasError: boolean; } function useLoadFonts({ fontData, loadFont }: Props): Output { const [isLoading, setIsLoading] = useState(true); const [hasError, setHasError] = useState(false); const loadedFonts = useRef(new Set<string>()); const loadFontCallback = useCallback( async (fontFamily: string) => { if (loadedFonts.current.has(fontFamily)) return; try { await loadFont(fontFamily); loadedFonts.current.add(fontFamily); } catch (error) { setHasError(true); } }, [loadFont] ); useEffect(() => { const fontFamilies = fontData.flatMap(({ fonts }) => fonts.flatMap((fontPack) => [fontPack.headerFontFamily, fontPack.bodyFontFamily]) ); const promises = fontFamilies .filter((fontFamily) => !loadedFonts.current.has(fontFamily)) .map((fontFamily) => retryPromise(() => loadFontCallback(fontFamily))); Promise.allSettled(promises).then(() => { setIsLoading(fontFamilies.some((fontFamily) => !loadedFonts.current.has(fontFamily))); }); }, [fontData, loadFontCallback]); return { isLoading, hasError }; } export default useLoadFonts;Here's a brief explanation of the changes made:
- Simplified font family collection: Instead of creating tuples and then flattening them, we directly collect all font families into a single array using
flatMap. - Improved
loadFontCallback: We added a check to see if the font is already loaded before attempting to load it. If it's already loaded, we simply return without doing anything. - Removed duplicate requests: By filtering out already loaded fonts in the
useEffecthook, we ensure that we don't make duplicate requests for the same font. - Simplified loading state update: We update the
isLoadingstate based on whether there are any fonts that haven't been loaded yet. If all fonts are loaded,isLoadingwill be set tofalse.
- Simplified font family collection: Instead of creating tuples and then flattening them, we directly collect all font families into a single array using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.