1
- import { useEffect } from 'preact/hooks' ;
1
+ import { useState , useEffect } from 'preact/hooks' ;
2
2
3
3
/**
4
4
* @typedef {Object } CacheEntry
@@ -13,11 +13,12 @@ export const CACHE = new Map();
13
13
export const createCacheKey = ( fn , deps ) => '' + fn + JSON . stringify ( deps ) ;
14
14
15
15
export function useResource ( fn , deps ) {
16
+ const update = useState ( { } ) [ 1 ] ;
16
17
const cacheKey = createCacheKey ( fn , deps ) ;
17
18
18
19
let state = CACHE . get ( cacheKey ) ;
19
20
if ( ! state ) {
20
- state = setupCacheEntry ( fn , cacheKey ) ;
21
+ state = setupCacheEntry ( fn , cacheKey , update ) ;
21
22
}
22
23
23
24
useEffect ( ( ) => {
@@ -39,9 +40,10 @@ export function useResource(fn, deps) {
39
40
/**
40
41
* @param {() => Promise<any> } fn
41
42
* @param {string } cacheKey
43
+ * @param {(state: CacheEntry) => void } [update]
42
44
* @returns {CacheEntry }
43
45
*/
44
- export function setupCacheEntry ( fn , cacheKey ) {
46
+ export function setupCacheEntry ( fn , cacheKey , update ) {
45
47
/** @type {CacheEntry } */
46
48
const state = { promise : fn ( ) , status : 'pending' , result : undefined , users : 0 } ;
47
49
@@ -54,6 +56,9 @@ export function setupCacheEntry(fn, cacheKey) {
54
56
. catch ( err => {
55
57
state . status = 'error' ;
56
58
state . result = err ;
59
+ } )
60
+ . finally ( ( ) => {
61
+ update && update ( state ) ;
57
62
} ) ;
58
63
} else {
59
64
state . status = 'success' ;
0 commit comments