Skip to main content

Function: withResource()

Call Signature

withResource<Input, ResourceValue>(resourceFactory): SignalStoreFeature<Input, ResourceResult<ResourceValue>>

Defined in: libs/ngrx-toolkit/src/lib/with-resource.ts:90

Experimental

Type Parameters

Input extends SignalStoreFeatureResult

ResourceValue

Parameters

resourceFactory

(store) => ResourceRef<ResourceValue>

A factory function that receives the store's state signals, methods, and props. Needs to return a ResourceRef.

Returns

SignalStoreFeature<Input, ResourceResult<ResourceValue>>

Description

Integrates a Resource into the SignalStore and makes the store instance implement the Resource interface.

The resource’s value is stored under the value key in the state and is exposed as a DeepSignal.

It can also be updated via patchState.

Usage Notes

const UserStore = signalStore(
withState({ userId: undefined as number | undefined }),
withResource(({ userId }) =>
httpResource<User>(() =>
userId === undefined ? undefined : `/users/${userId}`
)
)
);

const userStore = new UserStore();
userStore.value(); // User | undefined

Call Signature

withResource<Input, Dictionary>(resourceFactory): SignalStoreFeature<Input, NamedResourceResult<Dictionary>>

Defined in: libs/ngrx-toolkit/src/lib/with-resource.ts:132

Experimental

Type Parameters

Input extends SignalStoreFeatureResult

Dictionary extends ResourceDictionary

Parameters

resourceFactory

(store) => Dictionary

A factory function that receives the store's props, methods, and state signals. It must return a Record<string, ResourceRef>.

Returns

SignalStoreFeature<Input, NamedResourceResult<Dictionary>>

Description

Integrates multiple resources into the SignalStore. Each resource is registered by name, which is used as a prefix when spreading the members of Resource onto the store.

Each resource’s value is part of the state, stored under the value key with the resource name as prefix. Values are exposed as DeepSignals and can be updated via patchState.

Usage Notes

const UserStore = signalStore(
withState({ userId: undefined as number | undefined }),
withResource(({ userId }) => ({
list: httpResource<User[]>(() => '/users', { defaultValue: [] }),
detail: httpResource<User>(() =>
userId === undefined ? undefined : `/users/${userId}`
),
}))
);

const userStore = new UserStore();
userStore.listValue(); // []
userStore.detailValue(); // User | undefined