createComputedCache

See source code

Create a computed cache that works with any StoreObject (store or object containing a store). This is a standalone version of Store.createComputedCache that can work with multiple store instances.

function createComputedCache<
  Context extends StoreObject<any>,
  Result,
  Record extends StoreObjectRecordType<Context> =
    StoreObjectRecordType<Context>,
>(
  name: string,
  derive: (context: Context, record: Record) => Result | undefined,
  opts?: CreateComputedCacheOpts<Result, Record>,
): {
  get(context: Context, id: IdOf<Record>): Result | undefined;
};

Example

const expensiveCache = createComputedCache(
  "expensiveData",
  (context: { store: Store<Book> }, book: Book) => {
    return performExpensiveCalculation(book);
  },
);

// Use with different store instances
const result1 = expensiveCache.get(storeObject1, bookId);
const result2 = expensiveCache.get(storeObject2, bookId);

Parameters

NameDescription

name

string;

A unique name for the cache (used for debugging)

derive

(
  context: Context,
  record: Record,
) => Result | undefined;

Function that derives a value from the context and record

opts

CreateComputedCacheOpts<Result, Record>;

Optional configuration for equality checks

Returns

{
  get(context: Context, id: IdOf<Record>): Result | undefined;
};

A cache that can be used with multiple store instances

Prev
assertIdType
Next
createMigrationIds