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 456311f commit 8c40fd6
Showing 1 changed file with 28 additions and 27 deletions.
55 changes: 28 additions & 27 deletions src/hooks/useLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,57 +11,58 @@ export function useLoader<R>({initial, ...options}: CacheOptions<R>): R {
const loadedValue: R|undefined = cache.get<R>(options.cacheKey)?.result;
const [value, setValue] = useState(loadedValue !== undefined ? loadedValue : initial);
const mountedRef = useRef(true);
const initialRef = useRef(true);
const previousKey = useRef(options.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;

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

load();
});

useEffect(
() => {
if (initialRef.current) {
initialRef.current = false;

return;
if (previousKey.current !== options.cacheKey) {
reset();
previousKey.current = options.cacheKey;
}

reset();
},
[reset, options.cacheKey],
);

useEffect(
() => {
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;
}
}
load();

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

if (value === undefined) {
Expand Down

0 comments on commit 8c40fd6

Please sign in to comment.