29 lines
919 B
TypeScript
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 };
|
|
}
|