@saberhq/sail
Version:
Account caching and batched loading for React-based Solana applications.
84 lines • 3.19 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAccountsData = void 0;
const react_1 = require("react");
const use_debounce_1 = require("use-debounce");
const __1 = require("..");
const loadKeysFromCache = (getDatum, keys) => {
const ret = {};
keys.forEach((key) => {
if (key) {
ret[(0, __1.getCacheKeyOfPublicKey)(key)] = getDatum(key);
}
});
return ret;
};
/**
* Fetches data of the given accounts.
* @param keys Keys to fetch. Ensure that this is memoized or unlikely to change.
*
* @deprecated use {@link useBatchedParsedAccounts} instead
* @returns One of three types:
* - Buffer -- the account was found
* - null -- account not found or an error occurred while loading the account
* - undefined -- account key not provided or not yet loaded
*/
const useAccountsData = (keys) => {
const { getDatum, onBatchCache, fetchKeys, onError } = (0, __1.useSail)();
const [data, setData] = (0, react_1.useState)(() => loadKeysFromCache(getDatum, keys));
// TODO: add cancellation
const fetchAndSetKeys = (0, use_debounce_1.useDebouncedCallback)(async (fetchKeys, keys) => {
const keysData = await (0, __1.fetchKeysMaybe)(fetchKeys, keys);
const nextData = {};
keys.forEach((key, keyIndex) => {
if (key) {
const keyData = keysData[keyIndex];
if (keyData) {
nextData[(0, __1.getCacheKeyOfPublicKey)(key)] = keyData.data;
}
else {
nextData[(0, __1.getCacheKeyOfPublicKey)(key)] = keyData;
}
}
});
(0, react_1.startTransition)(() => {
setData(nextData);
});
}, 100);
(0, react_1.useEffect)(() => {
void (async () => {
var _a;
await ((_a = fetchAndSetKeys(fetchKeys, keys)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
onError(new __1.SailCacheRefetchError(e, keys));
}));
})();
}, [keys, fetchAndSetKeys, fetchKeys, onError]);
(0, __1.useAccountsSubscribe)(keys);
// refresh from the cache whenever the cache is updated
(0, react_1.useEffect)(() => {
return onBatchCache((e) => {
var _a;
if (keys.find((key) => key && e.hasKey(key))) {
void ((_a = fetchAndSetKeys(fetchKeys, keys)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
onError(new __1.SailCacheRefetchError(e, keys));
}));
}
});
}, [keys, fetchAndSetKeys, fetchKeys, onError, onBatchCache]);
// unload debounces when the component dismounts
(0, react_1.useEffect)(() => {
return () => {
fetchAndSetKeys.cancel();
};
}, [fetchAndSetKeys]);
return (0, react_1.useMemo)(() => {
return keys.map((key) => {
if (key) {
return data[(0, __1.getCacheKeyOfPublicKey)(key)];
}
return key;
});
}, [data, keys]);
};
exports.useAccountsData = useAccountsData;
//# sourceMappingURL=useAccountsData.js.map
;