Skip to content

Commit c70a003

Browse files
authored
fix: Correct 'useResource' suspense impl (#1247)
1 parent c9fb1b1 commit c70a003

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/lib/use-resource.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect } from 'preact/hooks';
1+
import { useState, useEffect } from 'preact/hooks';
22

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

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

1819
let state = CACHE.get(cacheKey);
1920
if (!state) {
20-
state = setupCacheEntry(fn, cacheKey);
21+
state = setupCacheEntry(fn, cacheKey, update);
2122
}
2223

2324
useEffect(() => {
@@ -39,9 +40,10 @@ export function useResource(fn, deps) {
3940
/**
4041
* @param {() => Promise<any>} fn
4142
* @param {string} cacheKey
43+
* @param {(state: CacheEntry) => void} [update]
4244
* @returns {CacheEntry}
4345
*/
44-
export function setupCacheEntry(fn, cacheKey) {
46+
export function setupCacheEntry(fn, cacheKey, update) {
4547
/** @type {CacheEntry} */
4648
const state = { promise: fn(), status: 'pending', result: undefined, users: 0 };
4749

@@ -54,6 +56,9 @@ export function setupCacheEntry(fn, cacheKey) {
5456
.catch(err => {
5557
state.status = 'error';
5658
state.result = err;
59+
})
60+
.finally(() => {
61+
update && update(state);
5762
});
5863
} else {
5964
state.status = 'success';

0 commit comments

Comments
 (0)