Skip to content

Commit

Permalink
Fix logic
Browse files Browse the repository at this point in the history
  • Loading branch information
marcospassos committed Oct 8, 2024
1 parent 8c40fd6 commit 895e67f
Showing 1 changed file with 27 additions and 32 deletions.
59 changes: 27 additions & 32 deletions src/hooks/useLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,61 +8,56 @@ export type CacheOptions<R> = EntryOptions<R> & {
};

export function useLoader<R>({initial, ...options}: CacheOptions<R>): R {
const loadedValue: R|undefined = cache.get<R>(options.cacheKey)?.result;
const {cacheKey} = options;
const loadedValue: R|undefined = cache.get<R>(cacheKey)?.result;
const [value, setValue] = useState(loadedValue !== undefined ? loadedValue : initial);
const mountedRef = useRef(true);
const previousKey = useRef(options.cacheKey);
const [previousCacheKey, setPreviousCacheKey] = useState(cacheKey);
const optionsRef = useRef(initial !== undefined ? options : undefined);

const load = useStableCallback(() => {
if (optionsRef.current !== undefined) {
try {
setValue(cache.load(optionsRef.current));
} catch (result: unknown) {
if (result instanceof Promise) {
result.then((resolvedValue: R) => {
if (mountedRef.current) {
setValue(resolvedValue);
}
});

return;
}

setValue(undefined);
}
}
});

const reset = useStableCallback(() => {
optionsRef.current = initial !== undefined ? options : undefined;

const newLoadedValue: R|undefined = cache.get<R>(options.cacheKey)?.result;
const newLoadedValue: R|undefined = cache.get<R>(cacheKey)?.result;

setValue(newLoadedValue !== undefined ? newLoadedValue : initial);

load();
});

useEffect(
() => {
if (previousKey.current !== options.cacheKey) {
if (cacheKey !== previousCacheKey) {
reset();
previousKey.current = options.cacheKey;
setPreviousCacheKey(cacheKey);
}
},
[reset, options.cacheKey],
[reset, cacheKey, previousCacheKey],
);

useEffect(
() => {
load();
if (optionsRef.current !== undefined) {
try {
setValue(cache.load(optionsRef.current));
} catch (result: unknown) {
if (result instanceof Promise) {
result.then((resolvedValue: R) => {
if (mountedRef.current) {
setValue(resolvedValue);
}
});

return;
}

setValue(undefined);
}
}

return () => {
mountedRef.current = false;
};
},
[load],
[previousCacheKey],
);

if (value === undefined) {
Expand All @@ -74,11 +69,11 @@ export function useLoader<R>({initial, ...options}: CacheOptions<R>): R {

type Callback = () => void;

function useStableCallback(cb: Callback): Callback {
function useStableCallback(callback: Callback): Callback {
const ref = useRef<Callback>();

useEffect(() => {
ref.current = cb;
ref.current = callback;
});

return useCallback(() => { ref.current?.(); }, []);
Expand Down

0 comments on commit 895e67f

Please sign in to comment.