How to use the @politie/sherlock.lens function in @politie/sherlock

To help you get started, we’ve selected a few @politie/sherlock examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github politie / sherlock / extensions / sherlock-utils / src / derivable-cache.ts View on Github external
get(key) {
            const cachedDerivable = cache.get(key);
            // If the cache has a hit for the current key, we know it is already connected (through another proxy).
            if (cachedDerivable) {
                return cachedDerivable.getState();
            }

            // A cache miss means no other proxy is currently connected.
            const newDerivable = _internal.independentTracking(() => derivableFactory(key));
            // We don't want final-value-optimalization, because that defeats the purpose of the cache. A final value
            // is not registered as an observed value, which means we cannot track the usage of our newly created derivable.
            // Therefore introduce a non-final atom (`atom(0)`) in the derivation:
            const derivable = isSettableDerivable(newDerivable)
                ? lens({ get: () => newDerivable.get(), set: v => newDerivable.set(v) }, atom(0))
                : atom(0).derive(() => newDerivable.get());

            if (delayedEviction) {
                derivable.autoCache();
            }

            // Get the state of our derivable early so it connects when needed.
            const state = derivable.getState();
            if (derivable.connected) {
                derivable[CACHED_PROXY] = this;
                cache.set(key, derivable);
                derivable.connected$.react(() => cache.delete(key), { skipFirst: true, once: true });
            }
            return state;
        },
        set(newValue, key) {
github politie / sherlock / extensions / sherlock-utils / src / derivable-cache.ts View on Github external
return key => {
        if (!isDerivable(key)) {
            const cacheItem = cache.get(key);
            if (cacheItem) {
                return cacheItem[CACHED_PROXY];
            }
        }

        return lens(descriptor, key);
    };
}