Files
narlblog/frontend/src/components/react/admin/editor/useAssetCache.ts
T
2026-05-17 14:44:45 +02:00

29 lines
919 B
TypeScript

import { useRef } from 'react';
import { getAssets } from '../../../../lib/api';
import type { Asset } from '../../../../lib/types';
/** Shared, lazily-populated asset list (used by autocomplete + upload). */
export function useAssetCache() {
const cacheRef = useRef<Asset[] | null>(null);
async function getCachedAssets(): Promise<Asset[]> {
if (cacheRef.current) return cacheRef.current;
const assets = await getAssets();
cacheRef.current = assets;
return assets;
}
// Mirrors the original behaviour: prepend only if the cache is already
// warm; if it's cold, leave it null so the next read refetches.
function prepend(newAssets: Asset[]) {
if (newAssets.length === 0) return;
cacheRef.current = cacheRef.current ? [...newAssets, ...cacheRef.current] : null;
}
function invalidate() {
cacheRef.current = null;
}
return { getCachedAssets, prepend, invalidate };
}