CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ngrx--store

RxJS powered Redux state management for Angular applications

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

action-creators.mddocs/

Action Creators

Action creators provide type-safe action creation with payload validation and support for organizing related actions into groups. They reduce boilerplate and ensure type safety throughout the application.

Capabilities

Create Action

Creates individual action creators with optional payloads.

/**
 * Creates a configured action creator function that returns an Action
 * @param type - Describes the action that will be dispatched
 * @returns ActionCreator function with type property
 */
function createAction<T extends string>(type: T): ActionCreator<T, () => Action<T>>;

/**
 * Creates a configured action creator function with props payload
 * @param type - Describes the action that will be dispatched  
 * @param config - Action creator props configuration
 * @returns ActionCreator function that accepts payload
 */
function createAction<T extends string, P extends object>(
  type: T,
  config: ActionCreatorProps<P> & NotAllowedCheck<P>
): ActionCreator<T, (props: P & NotAllowedCheck<P>) => P & Action<T>>;

/**
 * Creates a configured action creator function with custom creator
 * @param type - Describes the action that will be dispatched
 * @param creator - Custom creator function
 * @returns ActionCreator with custom parameters and return type
 */
function createAction<T extends string, P extends any[], R extends object>(
  type: T,
  creator: Creator<P, R & NotAllowedCheck<R>>
): FunctionWithParametersType<P, R & Action<T>> & Action<T>;

Usage Examples:

import { createAction, props } from "@ngrx/store";

// Simple action without payload
export const increment = createAction('[Counter] Increment');
export const reset = createAction('[Counter] Reset');

// Action with props payload
export const setValue = createAction(
  '[Counter] Set Value',
  props<{ value: number }>()
);

export const loadUser = createAction(
  '[User] Load User',
  props<{ userId: string }>()
);

export const loginSuccess = createAction(
  '[Auth] Login Success',
  props<{ user: User; token: string }>()
);

// Action with custom creator function
export const searchResults = createAction(
  '[Search] Results',
  (query: string, results: SearchResult[], timestamp = Date.now()) => ({
    query,
    results,
    timestamp,
    resultCount: results.length
  })
);

// Usage in components
store.dispatch(increment());
store.dispatch(setValue({ value: 42 }));
store.dispatch(loadUser({ userId: 'user-123' }));
store.dispatch(searchResults('angular', searchData));

Props Function

Defines payload structure for action creators.

/**
 * Creates props configuration for action creators
 * @returns ActionCreatorProps for type-safe payload definition
 */
function props<P extends SafeProps, SafeProps = NotAllowedInPropsCheck<P>>(): ActionCreatorProps<P>;

Union Function

Creates union types from multiple action creators for reducer type inference.

/**
 * Creates union type from action creators for type inference
 * @param creators - Dictionary of action creators
 * @returns Union type of all action creator return types
 */
function union<C extends { [key: string]: ActionCreator<string, Creator> }>(
  creators: C
): ReturnType<C[keyof C]>;

Usage Examples:

// Define action creators
const counterActions = {
  increment: createAction('[Counter] Increment'),
  decrement: createAction('[Counter] Decrement'),
  setValue: createAction('[Counter] Set Value', props<{ value: number }>())
};

// Create union type for reducer
type CounterActions = ReturnType<typeof union<typeof counterActions>>;

// Use in reducer
const counterReducer = createReducer(
  initialState,
  on(counterActions.increment, state => ({ ...state, count: state.count + 1 })),
  on(counterActions.setValue, (state, { value }) => ({ ...state, count: value }))
);

Create Action Group

Creates multiple related actions with a shared source prefix.

/**
 * Creates a group of action creators with the same source
 * @param config - Configuration object with source and events
 * @returns Dictionary of action creators with camelCase names
 */
function createActionGroup<Source extends string, Events extends Record<string, ActionCreatorProps<unknown> | Creator>>(
  config: ActionGroupConfig<Source, Events>
): ActionGroup<Source, Events>;

interface ActionGroupConfig<Source extends string, Events> {
  /** Source prefix for all actions in the group */
  source: Source;
  /** Dictionary of event names and their payload configurations */
  events: Events;
}

Usage Examples:

import { createActionGroup, props, emptyProps } from "@ngrx/store";

// Create action group for API operations
export const AuthApiActions = createActionGroup({
  source: 'Auth API',
  events: {
    // Action with payload using props
    'Login Success': props<{ user: User; token: string }>(),
    'Login Failure': props<{ error: string }>(),
    
    // Action without payload using emptyProps
    'Logout Success': emptyProps(),
    
    // Action with custom creator function
    'Session Expired': (reason: string, timestamp = Date.now()) => ({
      reason,
      timestamp
    }),
  },
});

// Generated action creators (camelCase names):
// AuthApiActions.loginSuccess({ user, token })
// AuthApiActions.loginFailure({ error })
// AuthApiActions.logoutSuccess()
// AuthApiActions.sessionExpired('timeout')

// Action types are formatted as "[Source] Event Name":
// "[Auth API] Login Success"
// "[Auth API] Login Failure"
// "[Auth API] Logout Success"
// "[Auth API] Session Expired"

// Usage in effects or components
store.dispatch(AuthApiActions.loginSuccess({ user: userData, token: authToken }));
store.dispatch(AuthApiActions.loginFailure({ error: 'Invalid credentials' }));
store.dispatch(AuthApiActions.logoutSuccess());

Empty Props

Creates empty props configuration for actions without payload.

/**
 * Creates empty props configuration for actions without payload
 * @returns ActionCreatorProps<void> for parameterless actions
 */
function emptyProps(): ActionCreatorProps<void>;

Type Definitions

Core Action Types

/**
 * Basic action interface with type property
 */
interface Action<Type extends string = string> {
  type: Type;
}

/**
 * Function that returns an object in the shape of Action interface
 */
type Creator<P extends any[] = any[], R extends object = object> = 
  FunctionWithParametersType<P, R>;

/**
 * Action creator function with type property
 */
type ActionCreator<T extends string = string, C extends Creator = Creator> = 
  C & Action<T>;

/**
 * Props configuration for action creators
 */
interface ActionCreatorProps<T> {
  _as: 'props';
  _p: T;
}

/**
 * Extract action type from action creator
 */
type ActionType<A> = A extends ActionCreator<infer T, infer C>
  ? ReturnType<C> & { type: T }
  : never;

/**
 * Function with specific parameters and return type
 */
type FunctionWithParametersType<P extends unknown[], R = void> = 
  (...args: P) => R;

Validation and Type Safety

Action creators include compile-time validation to prevent common mistakes:

// ❌ These will cause TypeScript errors:

// Arrays not allowed in props
const badAction1 = createAction(
  '[Bad] Action',
  props<string[]>() // Error: arrays not allowed
);

// Type property not allowed in props  
const badAction2 = createAction(
  '[Bad] Action', 
  props<{ type: string; data: any }>() // Error: type property not allowed
);

// Empty objects not allowed in props
const badAction3 = createAction(
  '[Bad] Action',
  props<{}>() // Error: empty objects not allowed
);

// ✅ Correct usage:
const goodAction = createAction(
  '[Good] Action',
  props<{ data: any; count: number }>()
);

Best Practices

  1. Use descriptive action types: Include the source/feature and specific operation
  2. Group related actions: Use createActionGroup for related API operations
  3. Type safety: Always use props<T>() for payload validation
  4. Consistent naming: Follow the pattern [Source] Operation for action types
  5. Avoid large payloads: Keep action payloads minimal and normalized

docs

action-creators.md

feature-management.md

index.md

module-configuration.md

reducer-creators.md

selectors.md

standalone-providers.md

store-service.md

testing-utilities.md

tile.json