UNPKG

@tobq/loadable

Version:

A library for simplifying asynchronous operations in React

850 lines (849 loc) 30 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.LoadError = exports.loading = exports.LoadingToken = void 0; exports.currentTimestamp = currentTimestamp; exports.useAbort = useAbort; exports.isLoadingValue = isLoadingValue; exports.hasLoaded = hasLoaded; exports.loadFailed = loadFailed; exports.map = map; exports.all = all; exports.toOptional = toOptional; exports.orElse = orElse; exports.isUsable = isUsable; exports.useLatestState = useLatestState; exports.useLoadable = useLoadable; exports.useThen = useThen; exports.useAllThen = useAllThen; exports.useLoadableWithCleanup = useLoadableWithCleanup; const react_1 = require("react"); /** * Returns the current time as a `TimeStamp`. * * @remarks * By default, this is just `Date.now()`. You can replace this with a custom * monotonic clock or high-resolution timer if desired. * * @returns The current time in milliseconds. * * @example * ```ts * const now = currentTimestamp() * console.log("The time is", now) * ``` * * @public */ function currentTimestamp() { return Date.now(); } /** * Provides a stable function that, when called, creates (or re-creates) * an `AbortController` and returns its `signal`. * * @remarks * Each render, the same function reference is returned. Calling it effectively * aborts any in-flight request and starts a fresh `AbortController`. * * @returns A function which, when called, returns a fresh `AbortSignal`. * * @example * ```ts * function MyComponent() { * const createAbortSignal = useAbort() * * useEffect(() => { * const signal = createAbortSignal() * fetch('/api', { signal }).catch(e => { ... }) * }, []) * ... * } * ``` * * @public */ function useAbort() { const abortControllerRef = (0, react_1.useRef)(null); return (0, react_1.useCallback)(() => { if (abortControllerRef.current) { // If we already had a controller, abort it abortControllerRef.current.abort(); } abortControllerRef.current = new AbortController(); return abortControllerRef.current.signal; }, []); } // ------------------------------------------------------------------- // Loading Symbol + LoadingToken // ------------------------------------------------------------------- /** * A class-based token to represent a unique "loading" state instance. * * @remarks * Using a `LoadingToken` instead of the default `loading` symbol allows you * to store additional metadata—e.g., timestamps, request IDs, etc. This can * facilitate debugging or concurrency strategies that rely on distinct tokens. * * @example * ```ts * import { LoadingToken } from "./useLoadable" * * const token = new LoadingToken() * console.log("Loading started at:", token.startTime) * ``` * * @public */ class LoadingToken { /** * Creates a new `LoadingToken`. * * @param startTime - When this token was created. Defaults to currentTimestamp(). */ constructor(startTime = currentTimestamp()) { this.startTime = startTime; } } exports.LoadingToken = LoadingToken; /** * A unique symbol representing a "loading" state. * * @remarks * This symbol is used by default in loadable data when an async request is in-flight. * Using a symbol is a simple approach for representing loading without additional metadata. * * @public */ exports.loading = Symbol("loading"); /** * Checks if the given value represents a "loading" state. * * @param value - The value to check. * @returns True if it’s either `loading` (symbol) or an instance of `LoadingToken`. * * @example * ```ts * if (isLoadingValue(loadable)) { * return <Spinner /> * } * ``` * * @public */ function isLoadingValue(value) { return value === exports.loading || value instanceof LoadingToken; } // ------------------------------------------------------------------- // Error for load failures // ------------------------------------------------------------------- /** * Represents an error that occurred while loading or fetching data. * * @remarks * Wraps the original `cause` and optionally overrides the error message. * * @example * ```ts * // If a fetch fails, we might return a LoadError instead of a generic Error. * throw new LoadError(err, "Failed to load user info") * ``` * * @public */ class LoadError extends Error { /** * Creates a new `LoadError`. * * @param cause - The underlying reason for the load failure (e.g., an Error object). * @param message - An optional descriptive message. Defaults to the cause’s message. */ constructor(cause, message) { super(message !== null && message !== void 0 ? message : (cause instanceof Error ? cause.message : String(cause))); this.cause = cause; } } exports.LoadError = LoadError; /** * Checks if a `Loadable<T>` has fully loaded (i.e., is neither loading nor an error). * * @param loadable - The loadable value to check. * @returns True if it’s the successful data of type `T`. * * @public */ function hasLoaded(loadable) { return !isLoadingValue(loadable) && !loadFailed(loadable); } /** * Checks if a `Loadable<T>` is a load failure (`LoadError`). * * @param loadable - The loadable value to check. * @returns True if it’s a `LoadError`. * * @public */ function loadFailed(loadable) { return loadable instanceof LoadError; } /** * Applies a mapper function to a loadable if it’s successfully loaded, returning a new loadable. * * @remarks * If `loadable` is an error or loading, it’s returned unchanged. * * @param loadable - The original loadable. * @param mapper - A function that transforms the loaded data `T` into `R`. * @returns A new loadable with data of type `R`, or the same loading/error state. * * @public */ function map(loadable, mapper) { if (loadFailed(loadable)) return loadable; if (isLoadingValue(loadable)) return loadable; return mapper(loadable); } /** * Combines multiple loadables into one. If any are still loading or have failed, returns `loading`. * * @remarks * In reality, `all()` returns `loading` if ANY have not loaded. If all are loaded, it returns an array * of their loaded values (typed to match each item in `loadables`). * * @param loadables - The loadable values to combine. * @returns A single loadable that is `loading` if any item is not loaded, else an array of loaded items. * * @example * ```ts * const combined = all(userLoadable, postsLoadable, statsLoadable) * if (!hasLoaded(combined)) { * return <Spinner /> * } * const [user, posts, stats] = combined * ``` * * @public */ function all(...loadables) { if (loadables.some(l => !hasLoaded(l))) { return exports.loading; } return loadables.map(l => l); } /** * Converts a loadable to `undefined` if not fully loaded, or the loaded value otherwise. * * @param loadable - The loadable value to unwrap. * @returns `T` if loaded, otherwise `undefined`. * * @public */ function toOptional(loadable) { return hasLoaded(loadable) ? loadable : undefined; } /** * Returns the loaded value if `loadable` is fully loaded, otherwise `defaultValue`. * * @param loadable - The loadable value to unwrap. * @param defaultValue - The fallback if loadable is not loaded. * @returns The loaded `T` or the provided `defaultValue`. * * @public */ function orElse(loadable, defaultValue) { return hasLoaded(loadable) ? loadable : defaultValue; } /** * Checks if a loadable is fully loaded AND not null/undefined. * * @param loadable - A loadable that could be `null` or `undefined` once loaded. * @returns True if the loadable is successfully loaded and non-nullish. * * @public */ function isUsable(loadable) { return hasLoaded(loadable) && loadable != null; } /** * Parses a `cache` field that could be a string or an object, returning a normalized object. * * @param cache - Either a string or `{ key, store }`. * @returns An object with `key` and `store`. * * @internal */ function parseCacheOption(cache) { var _a; if (!cache) { return { key: undefined, store: "localStorage" }; } if (typeof cache === "string") { // If user passed a string, that is the cache key, default to localStorage return { key: cache, store: "localStorage" }; } // Otherwise, user passed an object { key, store? } return { key: cache.key, store: (_a = cache.store) !== null && _a !== void 0 ? _a : "localStorage", }; } // ------------------------------------------------------------------- // Our caching utilities // ------------------------------------------------------------------- /** @internal */ const memoryCache = new Map(); /** * Reads data from the specified cache store. * * @internal * @param key - The cache key. * @param store - Which store to use ("memory", "localStorage", or "indexedDB"). * @returns The cached data or `undefined` if not found. */ function readCache(key, store) { return __awaiter(this, void 0, void 0, function* () { switch (store) { case "memory": { return memoryCache.get(key); } case "localStorage": { const json = window.localStorage.getItem(key); if (!json) return undefined; try { return JSON.parse(json); } catch (_a) { return undefined; } } case "indexedDB": { return yield readFromIndexedDB(key); } } }); } /** * Writes data to the specified cache store. * * @internal * @param key - The cache key. * @param data - The data to store. * @param store - The store to use. */ function writeCache(key, data, store) { return __awaiter(this, void 0, void 0, function* () { switch (store) { case "memory": { memoryCache.set(key, data); break; } case "localStorage": { window.localStorage.setItem(key, JSON.stringify(data)); break; } case "indexedDB": { yield writeToIndexedDB(key, data); break; } } }); } /** * Opens (and initializes) an IndexedDB database named "myReactCacheDB" with an object store "idbCache". * * @internal * @returns A promise resolving to the opened IDBDatabase. */ function openCacheDB() { return new Promise((resolve, reject) => { const request = indexedDB.open("myReactCacheDB", 1); request.onupgradeneeded = () => { const db = request.result; if (!db.objectStoreNames.contains("idbCache")) { db.createObjectStore("idbCache"); } }; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); } /** * Reads an item from the "idbCache" store in our "myReactCacheDB" IndexedDB. * * @internal */ function readFromIndexedDB(key) { return __awaiter(this, void 0, void 0, function* () { const db = yield openCacheDB(); return new Promise((resolve, reject) => { const tx = db.transaction("idbCache", "readonly"); const store = tx.objectStore("idbCache"); const getReq = store.get(key); getReq.onsuccess = () => resolve(getReq.result); getReq.onerror = () => reject(getReq.error); }); }); } /** * Writes an item to the "idbCache" store in our "myReactCacheDB" IndexedDB. * * @internal */ function writeToIndexedDB(key, data) { return __awaiter(this, void 0, void 0, function* () { const db = yield openCacheDB(); return new Promise((resolve, reject) => { const tx = db.transaction("idbCache", "readwrite"); const store = tx.objectStore("idbCache"); const putReq = store.put(data, key); putReq.onsuccess = () => resolve(); putReq.onerror = () => reject(putReq.error); }); }); } // ------------------------------------------------------------------- // A custom hook for state with timestamps // ------------------------------------------------------------------- /** * A hook that manages a piece of state (`T`) alongside a timestamp, allowing you * to ignore stale updates with older timestamps. * * @remarks * Internally, it stores the current `value` plus a `loadStart` timestamp. Each time * you set a new value, you can provide an optional new timestamp. If that timestamp * is older than the current state's `loadStart`, the update is ignored. * * @param initial - The initial state value. * @returns A tuple: `[value, setValue, loadStart]`. * * @example * ```ts * const [myValue, setMyValue, lastUpdated] = useLatestState(0) * * function handleUpdate(newVal: number) { * // We'll pass a timestamp * setMyValue(newVal, performance.now()) * } * ``` * * @public */ function useLatestState(initial) { const [value, setValue] = (0, react_1.useState)({ value: initial, loadStart: 0, }); function updateValue(newValue, loadStart = currentTimestamp()) { setValue(current => { if (current.loadStart > loadStart) { // Ignore older updates return current; } const nextValue = typeof newValue === "function" ? newValue(current.value) : newValue; return { value: nextValue, loadStart, }; }); } return [value.value, updateValue, value.loadStart]; } // ------------------------------------------------------------------- // For debugging (optional) // ------------------------------------------------------------------- /** * A Set of timestamps indicating which requests are currently in-flight. * * @remarks * This is used internally for debugging and to signal "prerenderReady" when no requests remain. * Attach it to `window` in dev environments if desired. * * @internal */ const currentlyLoading = new Set(); // @ts-ignore if (typeof window !== "undefined") { ; window.currentlyLoading = currentlyLoading; } /** * The core hook that returns a `Loadable<T>` by calling an async fetcher. * * @remarks * Has two main usage patterns: * 1. **Waitable** form: You pass a "waitable" value plus a `readyCondition`, and a `fetcher`. * - The effect only runs when `readyCondition(waitable)` is true. * - If `hideReload` is false, it will revert to loading each time the waitable changes. * * 2. **Simple** form: You pass just a `fetcher`, dependencies, and optional `UseLoadableOptions`. * - The fetcher is called whenever dependencies change. * - The result is stored in a loadable: `loading` until success or `LoadError` on failure. * * Caching: * - If `cache` is provided (string or `{ key, store }`), it tries to read from that cache first. * If found, returns it immediately. Then (optionally) re-fetches in the background, or * according to `hideReload`. * * @typeParam T - The successful data type when using the simple form. * @typeParam W - The waitable type (for advanced usage). * @typeParam R - The successful data type when using the waitable form. * * @public */ function useLoadable(fetcherOrWaitable, depsOrReadyCondition, optionsOrFetcher, dependencies = [], lastParam) { // ============================ // CASE 1: waitable + readyCondition + fetcher // ============================ if (typeof depsOrReadyCondition === "function") { const waitable = fetcherOrWaitable; const readyCondition = depsOrReadyCondition; const fetcher = optionsOrFetcher; let onErrorCb; let hideReload = false; let cacheObj = { key: undefined, store: "localStorage", }; if (typeof lastParam === "function") { onErrorCb = lastParam; } else if (lastParam && typeof lastParam === "object") { onErrorCb = lastParam.onError; hideReload = !!lastParam.hideReload; cacheObj = parseCacheOption(lastParam.cache); } const [value, setValue] = useLatestState(exports.loading); const abort = useAbort(); const ready = readyCondition(waitable); (0, react_1.useEffect)(() => { const startTime = currentTimestamp(); // If hideReload=false or not yet loaded, revert to 'loading' if (!hideReload || !hasLoaded(value)) { setValue(exports.loading, startTime); } if (ready) { // Before fetching, try reading from cache (if provided) if (cacheObj.key) { // Attempt to read ; (() => __awaiter(this, void 0, void 0, function* () { const cachedData = yield readCache(cacheObj.key, cacheObj.store); if (cachedData !== undefined) { // We found a valid cached value // You could do stale-while-revalidate or just set it: setValue(cachedData, startTime); } doFetch(); }))(); } else { doFetch(); } function doFetch() { currentlyLoading.add(startTime); const signal = abort(); fetcher(waitable, signal) .then(result => { // On success, write to cache if key if (cacheObj.key) { writeCache(cacheObj.key, result, cacheObj.store).catch(console.error); } setValue(result, startTime); }) .catch(e => { onErrorCb === null || onErrorCb === void 0 ? void 0 : onErrorCb(e); setValue(new LoadError(e), startTime); }) .finally(() => { currentlyLoading.delete(startTime); if (currentlyLoading.size === 0 && typeof window !== "undefined" && "prerenderReady" in window) { ; window.prerenderReady = true; } }); } } return () => { abort(); currentlyLoading.delete(startTime); }; }, [...dependencies, ready, hideReload]); return value; } // ============================ // CASE 2: fetcher + deps + options // ============================ const fetcher = fetcherOrWaitable; const deps = depsOrReadyCondition; const options = optionsOrFetcher; // Parse the cache field const { key: cacheKey, store: cacheStore } = parseCacheOption(options === null || options === void 0 ? void 0 : options.cache); // We'll piggyback on the waitable approach, with a "dummy" waitable always ready return useLoadable(exports.loading, () => true, (_ignored, signal) => __awaiter(this, void 0, void 0, function* () { // // 1) Attempt to read from cache (if we have cacheKey) // if (cacheKey) { const cachedData = yield readCache(cacheKey, cacheStore); if (cachedData !== undefined) { // Found a valid cached value return cachedData; } } // // 2) If there's a prefetched loadable // if ((options === null || options === void 0 ? void 0 : options.prefetched) !== undefined) { if (options.prefetched === exports.loading) { return fetcher(signal); } else if (options.prefetched instanceof LoadError) { throw options.prefetched; } else if (isLoadingValue(options.prefetched)) { // e.g. a LoadingToken return fetcher(signal); } else { // Otherwise it's a T if (cacheKey) { yield writeCache(cacheKey, options.prefetched, cacheStore); } return options.prefetched; } } // // 3) Normal fetch // const data = yield fetcher(signal); if (cacheKey) { yield writeCache(cacheKey, data, cacheStore); } return data; }), deps, { onError: options === null || options === void 0 ? void 0 : options.onError, hideReload: options === null || options === void 0 ? void 0 : options.hideReload, }); } // ------------------------------------------------------------------- // useThen + useAllThen // ------------------------------------------------------------------- /** * A hook that waits for a `loadable` to finish, then calls another async `fetcher`. * * @remarks * If `loadable` is still loading or has failed, this hook returns the same `loadable` state. * Otherwise, if `loadable` is loaded, it calls `fetcher(loadedValue)` and returns the result * as a new `Loadable<R>`. * * @param loadable - The initial loadable value. * @param fetcher - A function that takes the successfully loaded data plus an abort signal, returning a promise. * @param dependencies - An optional list of dependencies to trigger re-runs. Defaults to `[hasLoaded(loadable)]`. * @param options - Optional `UseLoadableOptions` for error handling, caching, etc. * @returns A `Loadable<R>` that is `loading` until the chained fetch finishes, or a `LoadError` if it fails. * * @example * ```ts * const user = useLoadable(() => fetchUser(userId), [userId]) * const posts = useThen(user, (u) => fetchPostsForUser(u.id)) * ``` * * @public */ function useThen(loadable, fetcher, dependencies = [hasLoaded(loadable)], options) { return useLoadable(loadable, l => hasLoaded(l), (val, abort) => __awaiter(this, void 0, void 0, function* () { return map(val, v => fetcher(v, abort)); }), dependencies, options); } /** * A hook that waits for multiple loadables to finish, then calls a `fetcher` using all their loaded values. * * @remarks * Internally, it calls `all(...loadables)`. If any loadable is still loading or fails, the combined is `loading`. * Once all are loaded, calls `fetcher(...loadedValues, signal)` and returns a `Loadable<R>`. * * @param loadables - An array (spread) of loadable values, e.g. `[user, stats, posts]`. * @param fetcher - A function that takes each loaded value plus an `AbortSignal`. * @param dependencies - An optional list of dependencies to re-run the effect. Defaults to the loadables array. * @param options - Optional config for error handling, caching, etc. * @returns A loadable result of type `R`. * * @example * ```ts * const user = useLoadable(fetchUser, []) * const stats = useLoadable(fetchStats, []) * * const combined = useAllThen( * [user, stats], * (u, s, signal) => fetchDashboard(u, s, signal), * [] * ) * ``` * * @public */ function useAllThen(loadables, fetcher, dependencies = loadables, options) { const combined = all(...loadables); return useThen(combined, (vals, signal) => fetcher(...vals, signal), dependencies, options); } /** * A variant of `useLoadable` that returns a `[Loadable<T>, cleanupFunc]` tuple. * * @remarks * This lets you manually call `cleanupFunc()` to abort any in-flight request, * instead of waiting for an unmount or effect re-run. * * @returns A tuple: `[Loadable<T>, cleanupFunc]`. * * @example * ```ts * const [userLoadable, cleanup] = useLoadableWithCleanup(fetchUser, []) * * // Manually abort the current fetch: * cleanup() * ``` * * @public */ function useLoadableWithCleanup(fetcherOrWaitable, depsOrReadyCondition, optionsOrFetcher, dependencies = [], lastParam) { const [value, setValue] = useLatestState(exports.loading); const abortControllerRef = (0, react_1.useRef)(null); let isCase1 = false; let waitableVal; let readyFn; let actualFetcher; let hideReload = false; let onErrorCb; let deps; let cacheObj = parseCacheOption(); if (typeof depsOrReadyCondition === "function") { // CASE 1 isCase1 = true; waitableVal = fetcherOrWaitable; readyFn = depsOrReadyCondition; actualFetcher = optionsOrFetcher; deps = dependencies; if (typeof lastParam === "function") { onErrorCb = lastParam; } else if (lastParam && typeof lastParam === "object") { onErrorCb = lastParam.onError; hideReload = !!lastParam.hideReload; cacheObj = parseCacheOption(lastParam.cache); } } else { // CASE 2 const fetcher = fetcherOrWaitable; deps = depsOrReadyCondition; const options = optionsOrFetcher; onErrorCb = options === null || options === void 0 ? void 0 : options.onError; hideReload = !!(options === null || options === void 0 ? void 0 : options.hideReload); cacheObj = parseCacheOption(options === null || options === void 0 ? void 0 : options.cache); // always "ready" readyFn = () => true; // The actual fetcher that either reads from cache or calls the original fetcher actualFetcher = (_ignored, signal) => __awaiter(this, void 0, void 0, function* () { // Read from cache if possible if (cacheObj.key) { const cachedData = yield readCache(cacheObj.key, cacheObj.store); if (cachedData !== undefined) { return cachedData; } } // If prefetched is available if ((options === null || options === void 0 ? void 0 : options.prefetched) !== undefined) { if (options.prefetched === exports.loading) { return fetcher(signal); } else if (options.prefetched instanceof LoadError) { throw options.prefetched; } else if (isLoadingValue(options.prefetched)) { return fetcher(signal); } else { // T if (cacheObj.key) { yield writeCache(cacheObj.key, options.prefetched, cacheObj.store); } return options.prefetched; } } // Normal fetch const data = yield fetcher(signal); if (cacheObj.key) { yield writeCache(cacheObj.key, data, cacheObj.store); } return data; }); } (0, react_1.useEffect)(() => { var _a; const startTime = currentTimestamp(); const isReady = (_a = readyFn === null || readyFn === void 0 ? void 0 : readyFn(waitableVal)) !== null && _a !== void 0 ? _a : true; // If hideReload=false or current is not loaded, revert to 'loading' if (!hideReload || !hasLoaded(value)) { setValue(exports.loading, startTime); } if (isReady && actualFetcher) { abortControllerRef.current = new AbortController(); const signal = abortControllerRef.current.signal; currentlyLoading.add(startTime); actualFetcher(waitableVal, signal) .then(result => { setValue(result, startTime); }) .catch(e => { onErrorCb === null || onErrorCb === void 0 ? void 0 : onErrorCb(e); setValue(new LoadError(e), startTime); }) .finally(() => { currentlyLoading.delete(startTime); if (currentlyLoading.size === 0 && typeof window !== "undefined" && "prerenderReady" in window) { ; window.prerenderReady = true; } }); } return () => { var _a; (_a = abortControllerRef.current) === null || _a === void 0 ? void 0 : _a.abort(); currentlyLoading.delete(startTime); }; }, [ isCase1, waitableVal, readyFn, actualFetcher, hideReload, onErrorCb, value, setValue, ...deps, ]); /** * Cancels any current request immediately. This is the second element * in the returned tuple from `useLoadableWithCleanup`. */ const cleanupFunc = (0, react_1.useCallback)(() => { var _a; (_a = abortControllerRef.current) === null || _a === void 0 ? void 0 : _a.abort(); }, []); return [value, cleanupFunc]; }