UNPKG

@rocketmakers/api-swr

Version:

Rocketmakers front-end library for parsing a generated Typescript API client into a set of configurable React hooks for fetching and mutating data.

53 lines (52 loc) 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCacheManager = void 0; const tslib_1 = require("tslib"); const swr_1 = require("swr"); const React = tslib_1.__importStar(require("react")); /** * A hook to get the global mutate function from `swr` and a custom mutate function for infinite queries * @returns The global mutate function and the custom mutate function for infinite queries */ const useCacheManager = () => { const _a = (0, swr_1.useSWRConfig)(), { mutate, cache } = _a, restOfSwrConfig = tslib_1.__rest(_a, ["mutate", "cache"]); /** * A function to mutate infinite queries based on a key match * @param key The string key to match against (usually obtained via the `cacheKey` method on a controller endpoint) * @param rest The rest of the parameters to pass to `mutate` * @returns The result of the mutation */ const mutateInfinite = React.useCallback((key, ...rest) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { yield Promise.all(Array.from(cache.keys()) .filter((k) => k.includes(key)) .map((k) => mutate(k, ...rest))); }), []); /** * A function to perform a simple invalidation and request new data for a given key * This is just a wrapper around `mutate` with only the key argument, added for semantic clarity * @param key The key to invalidate * @returns The result of the SWR mutation */ const invalidate = React.useCallback((key) => { return mutate(key); }, [mutate]); /** * A function to perform a simple invalidation and request new data for a given key * Designed for use with infinite queries, the key only needs to be the `cacheKey` of the endpoint, the `startsWith` invalidator is not needed here. * This is just a wrapper around `mutate` with only the key argument, added for semantic clarity * @param key The key to invalidate * @returns The result of the SWR mutation */ const invalidateInfinite = React.useCallback((key) => { return mutateInfinite(key); }, [mutateInfinite]); /** * A function to clear all cache entries * @returns The result of the SWR mutation */ const clearAll = React.useCallback(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () { yield Promise.all(Array.from(cache.keys()).map((key) => mutate(key, undefined, { revalidate: false }))); }), [cache, mutate]); return Object.assign({ mutate, mutateInfinite, invalidate, invalidateInfinite, cache, clearAll }, restOfSwrConfig); }; exports.useCacheManager = useCacheManager;