import { STATE_SOURCE, WritableStateSource } from './state-source';
import {
EmptyFeatureResult,
SignalStoreFeature,
SignalStoreFeatureResult,
StateSignals,
} from './signal-store-models';
import { Prettify } from './ts-helpers';
type HookFn = (
store: Prettify<
StateSignals &
Input['props'] &
Input['methods'] &
WritableStateSource
>
) => void;
type HooksFactory = (
store: Prettify<
StateSignals &
Input['props'] &
Input['methods'] &
WritableStateSource
>
) => {
onInit?: () => void;
onDestroy?: () => void;
};
export function withHooks(hooks: {
onInit?: HookFn;
onDestroy?: HookFn;
}): SignalStoreFeature;
export function withHooks(
hooks: HooksFactory
): SignalStoreFeature;
/**
* @description
*
* Adds lifecycle hooks to a SignalStore.
* Supports an onInit hook that executes when the store is initialized.
* Supports an onDestroy hook for when the store is destroyed.
*
* @usageNotes
*
* ```ts
* import { signalStore, withHooks, withState } from '@ngrx/signals';
*
* export const UserStore = signalStore(
* withState({ firstName: 'Jimi', lastName: 'Hendrix' }),
* withHooks({
* onInit({ firstName }) {
* console.log('first name on init', firstName());
* },
* onDestroy({ lastName }) {
* console.log('last name on destroy', lastName());
* },
* })
* );
* ```
*/
export function withHooks(
hooksOrFactory:
| {
onInit?: HookFn;
onDestroy?: HookFn;
}
| HooksFactory
): SignalStoreFeature {
return (store) => {
const storeMembers = {
[STATE_SOURCE]: store[STATE_SOURCE],
...store.stateSignals,
...store.props,
...store.methods,
};
const hooks =
typeof hooksOrFactory === 'function'
? hooksOrFactory(storeMembers)
: hooksOrFactory;
const mergeHooks = (currentHook?: () => void, hook?: HookFn) => {
return hook
? () => {
if (currentHook) {
currentHook();
}
hook(storeMembers);
}
: currentHook;
};
return {
...store,
hooks: {
onInit: mergeHooks(store.hooks.onInit, hooks.onInit),
onDestroy: mergeHooks(store.hooks.onDestroy, hooks.onDestroy),
},
};
};
}