All Downloads are FREE. Search and download functionalities are using the official Maven repository.

package.subscription.dist.index.js Maven / Gradle / Ivy

There is a newer version: 2.2.5
Show newest version
Object.defineProperty(exports, '__esModule', { value: true });

var useSWR = require('swr');
var _internal = require('swr/_internal');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var useSWR__default = /*#__PURE__*/_interopDefaultLegacy(useSWR);

const subscriptionStorage = new WeakMap();
const SUBSCRIPTION_PREFIX = '$sub$';
const subscription = (useSWRNext)=>{
    return (_key, subscribe, config)=>{
        const [key] = _internal.serialize(_key);
        // Prefix the key to avoid conflicts with other SWR resources.
        const subscriptionKey = key ? SUBSCRIPTION_PREFIX + key : undefined;
        const swr = useSWRNext(subscriptionKey, null, config);
        const { cache  } = config;
        // Ensure that the subscription state is scoped by the cache boundary, so
        // you can have multiple SWR zones with subscriptions having the same key.
        if (!subscriptionStorage.has(cache)) {
            subscriptionStorage.set(cache, [
                new Map(),
                new Map()
            ]);
        }
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const [subscriptions, disposers] = subscriptionStorage.get(cache);
        _internal.useIsomorphicLayoutEffect(()=>{
            if (!subscriptionKey) return;
            const [, set] = _internal.createCacheHelper(cache, subscriptionKey);
            const refCount = subscriptions.get(subscriptionKey) || 0;
            const next = (error, data)=>{
                if (error !== null && typeof error !== 'undefined') {
                    set({
                        error
                    });
                } else {
                    set({
                        error: undefined
                    });
                    swr.mutate(data, false);
                }
            };
            // Increment the ref count.
            subscriptions.set(subscriptionKey, refCount + 1);
            if (!refCount) {
                const dispose = subscribe(key, {
                    next
                });
                if (typeof dispose !== 'function') {
                    throw new Error('The `subscribe` function must return a function to unsubscribe.');
                }
                disposers.set(subscriptionKey, dispose);
            }
            return ()=>{
                // Prevent frequent unsubscribe caused by unmount
                setTimeout(()=>{
                    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                    const count = subscriptions.get(subscriptionKey) - 1;
                    subscriptions.set(subscriptionKey, count);
                    // Dispose if it's the last one.
                    if (!count) {
                        const dispose = disposers.get(subscriptionKey);
                        dispose == null ? void 0 : dispose();
                    }
                });
            };
        // eslint-disable-next-line react-hooks/exhaustive-deps
        }, [
            subscriptionKey
        ]);
        return {
            get data () {
                return swr.data;
            },
            get error () {
                return swr.error;
            }
        };
    };
};
/**
 * A hook to subscribe a SWR resource to an external data source for continuous updates.
 * @experimental This API is experimental and might change in the future.
 * @example
 * ```jsx
 * import useSWRSubscription from 'swr/subscription'
 *
 * const { data, error } = useSWRSubscription(key, (key, { next }) => {
 *   const unsubscribe = dataSource.subscribe(key, (err, data) => {
 *     next(err, data)
 *   })
 *   return unsubscribe
 * })
 * ```
 */ const useSWRSubscription = _internal.withMiddleware(useSWR__default["default"], subscription);

exports["default"] = useSWRSubscription;
exports.subscription = subscription;




© 2015 - 2024 Weber Informatics LLC | Privacy Policy