Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions src/lib/use-resource.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from 'preact/hooks';
import { useState, useEffect } from 'preact/hooks';

/**
* @typedef {Object} CacheEntry
Expand All @@ -13,11 +13,12 @@ export const CACHE = new Map();
export const createCacheKey = (fn, deps) => '' + fn + JSON.stringify(deps);

export function useResource(fn, deps) {
const update = useState({})[1];
const cacheKey = createCacheKey(fn, deps);

let state = CACHE.get(cacheKey);
if (!state) {
state = setupCacheEntry(fn, cacheKey);
state = setupCacheEntry(fn, cacheKey, update);
}

useEffect(() => {
Expand All @@ -39,9 +40,10 @@ export function useResource(fn, deps) {
/**
* @param {() => Promise<any>} fn
* @param {string} cacheKey
* @param {(state: CacheEntry) => void} [update]
* @returns {CacheEntry}
*/
export function setupCacheEntry(fn, cacheKey) {
export function setupCacheEntry(fn, cacheKey, update) {
/** @type {CacheEntry} */
const state = { promise: fn(), status: 'pending', result: undefined, users: 0 };

Expand All @@ -54,6 +56,9 @@ export function setupCacheEntry(fn, cacheKey) {
.catch(err => {
state.status = 'error';
state.result = err;
})
.finally(() => {
update && update(state);
});
} else {
state.status = 'success';
Expand Down