Skip to main content
Version: Next (2.x)

createContextStoreWithLoader()

createContextStoreWithLoader<Result, Context, Args>(key, loader, options?): readonly [(ctx) => Promise<Result>, (ctx, ...args) => void]

Creates a context store for managing asynchronous values within the context object. See https://baeta.io/docs/guides/context-store

Type Parameters

Type ParameterDefault type

Result

Context

unknown

Args extends unknown[]

unknown[]

Parameters

ParameterTypeDescription

key

symbol

A unique symbol to identify the stored value in the context

loader

(ctx, ...args) => Result | PromiseLike<Result>

A function that returns the value for the store

options?

ContextStoreOptions

Configuration options for the store

Returns

readonly [(ctx) => Promise<Result>, (ctx, ...args) => void]

A tuple containing get and load functions for managing the stored value

Example

// Create a store for user data
const userStoreKey = Symbol('userStore');
const [getUser, initUserStore] = createContextStoreWithLoader(userStoreKey, (userId: string) => { return fetchUser(userId); }, { lazy: true });

// Initialize the store when you create the context
initUserStore(ctx, userId);

// Later, retrieve the user in a resolver
const user = await getUser(ctx);