npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-view-state

v3.0.1

Published

ngx-view-state is a library for managing the Loading/Success/Error states of views in Angular applications that use Ngrx or HttpClient

Downloads

10

Readme

The ngx-view-state library is designed to simplify managing view states(Loading, Success, Error) of HTTP requests in Angular applications that use NGRX.

This library provides set of utils that allow developers to handle different view states such as loading, error, and loaded states.

Overview

Stackblitz Example

Medium blog post

Installation

Run: npm install ngx-view-state

Usage With Ngrx

  1. Create view state feature and pass generic type for the error state
// view-state.feature.ts
import { createViewStateFeature } from 'ngx-view-state';

export const { 
    viewStatesFeature, 
    selectActionViewStatus, 
    selectIsAnyActionLoading 
} = createViewStateFeature<string>()
  1. Provide the viewStateFeature and ViewStateEffect in the root
// app.config.ts

import { provideState, provideStore } from '@ngrx/store';
import { provideEffects } from '@ngrx/effects';
import { viewStatesFeature } from './store/view-state.feature';
import { ViewStateEffects } from 'ngx-view-state';

export const appConfig: ApplicationConfig = {
	providers: [
		provideStore({}),
		provideState(viewStatesFeature),
		provideEffects(ViewStateEffects),
	]
};
  1. Register actions in your effect to mark them as view state actions
// todos.effects.ts

import { ViewStateActionsService } from 'ngx-view-state';

@Injectable()
export class TodosEffects {

constructor(private actions$: Actions, private viewStateActionsService: ViewStateActionsService) {
	this.viewStateActionsService.add([
		{
		  startLoadingOn: TodosActions.loadTodos,
		  resetOn: [TodosActions.loadTodosSuccess],
		  errorOn: [TodosActions.loadTodosFailure]
		},
		{
		  startLoadingOn: TodosActions.addTodo,
		  resetOn: [TodosActions.addTodoSuccess],
		  errorOn: [TodosActions.addTodoFailure]
		},
		// Update and delete actions can be added in the same way
            ]);
    }
}
  1. Create view state selectors
// todos.selectors.ts

import { selectActionViewStatus, selectIsAnyActionLoading } from '../../store/view-state.feature';
import { TodosActions } from './todos.actions';

// Select loading/error/idle status of the loadTodos action
export const selectTodosViewStatus = selectActionViewStatus(TodosActions.loadTodos);

// To display an overlay when any of the actions are loading
export const selectIsTodosActionLoading = selectIsAnyActionLoading(TodosActions.addTodo, TodosActions.updateTodo, TodosActions.deleteTodo);
  1. Make use of previously created selectors and dispatch the load action.
// todos.component.ts

import { selectTodos } from './store/todos.feature';
import { selectTodosViewStatus, selectIsTodosActionLoading } from './store/todos.selectors';
import { ViewStateDirective } from 'ngx-view-state';

@Component({
	selector: 'app-todos',
	standalone: true,
	imports: [ViewStateDirective],
	templateUrl: './todos.component.html',
	styleUrl: './todos.component.css'
})
export class TodosComponent {
	public todos$ = this.store.select(selectTodos);
	
	public viewState$ = this.store.select(selectTodosViewStatus);
	public isOverlayLoading$ = this.store.select(selectIsTodosActionLoading);

	constructor(private store: Store) {
		this.store.dispatch(TodosActions.loadTodos());
	}

Usage ngxViewState directive

Import the ViewStateDirective in your component and pass the view state value to the directive.

<!-- todos.component.html -->
<ng-container *ngxViewState="viewState$ | async">
    <table *ngIf="todos$ | async as todos" mat-table [dataSource]="todos">
        // Render todos
    </table>
  <div class="loading-shade" *ngIf="isOverlayLoading$ | async">
	<app-loading></app-loading>
   </div>
</ng-container>

Directive will then render the appropriate component based on the view state value.

Components customization

You can provide your own components by using the provideLoadingStateComponent and provideErrorStateComponent functions.

By default, the library uses the ngx-view-state components with simple template

// app.config.ts

import { provideLoadingStateComponent, provideErrorStateComponent } from 'ngx-view-state';

export const appConfig: ApplicationConfig = {
	providers: [
            // ...
            provideLoadingStateComponent(LoadingComponent),
            provideErrorStateComponent(ErrorComponent)
	]
};

Usage with HttpClient

mapToViewModel is a utility function that can be used to map the response of an HTTP request to a ComponentViewModel interface that is compatible with the ngxViewState directive.


import { mapToViewModel } from 'ngx-view-state';

@Injectable()
export class TodosService {
    constructor(private http: HttpClient) {}

    loadTodos(): Observable<ComponentViewModel<Todo[]>> {
        return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos').pipe(
            mapToViewModel()
        );
    }
}

And then in your component, you can use the ngxViewState directive to handle the view state of the HTTP request.

// todos.component.ts

import { TodosService } from './todos.service';

@Component({
    selector: 'app-todos',
    standalone: true,
    imports: [ViewStateDirective],
    templateUrl: './todos.component.html',
    styleUrl: './todos.component.css'
})
export class TodosComponent {
    public todos$ = this.todosService.loadTodos();

    constructor(private todosService: TodosService) {}
}
<!-- todos.component.html -->
<ng-container *ngxViewState="todos$ as todos">
    <table mat-table [dataSource]="todos.data">
        // Render todos
    </table>
</ng-container>

You can also perform custom mapping by passing an object with onSuccess and onError handlers to the mapToViewModel function.

import { mapToViewModel } from 'ngx-view-state';


loadTodos(): Observable<ComponentViewModel<Todo[]>> {
        return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos').pipe(
            mapToViewModel({
                onSuccess: (data) => ({ viewStatus: loadedViewStatus(), data: data.map(...) }),
                onError: (error) => ({ viewStatus: errorViewStatus('Failed to load todos') })
            }
        );
    }

Documentation

createViewStateFeature

Creates a feature that holds the view state of the actions.

State interface:

export interface ViewState<E> {
	actionType: string;
	viewStatus: ViewStatus<E>;
}

Where E generic is the type of the error state.

  • actionType is the static type property of the action.
  • viewStatus is the view state of the action.

Returns an object with the following properties:

  • initialState - Initial state of the view state feature.
  • viewStatesFeatureName - Name of the view state feature.
  • viewStatesFeature - Ngrx feature that holds the view state of the actions.

Selectors:

  • selectViewStateEntities - returns the view state entities.
  • selectViewStateActionTypes - returns the view state action types (TodosActions.loadTodos.type).
  • selectAllViewState - returns all view states.
  • selectActionViewStatus - returns the view status of the action.
  • selectViewState - returns the view state entity by action type.
  • selectIsAnyActionLoading - returns whether any of the provided actions are in LOADING state.
  • selectIsAnyActionLoaded - returns whether any of the provided actions are in LOADED state.
  • selectIsAnyActionError - returns whether any of the provided actions are in ERROR state.
  • selectIsAnyActionIdle - returns whether any of the provided actions are in IDLE state.

ViewStateActions

Action group to work with the view state reducer

export const ViewStateActions = createActionGroup({
	source: 'ViewState',
	events: {
		startLoading: props<{ actionType: string }>(),
		reset: props<{ actionType: string }>(),
		resetMany: props<{ actionTypes: string[] }>(),
		error: props<{ actionType: string; error?: unknown }>(),
		errorMany: props<{ actionTypes: { actionType: string, error?: unknown }[] }>()
	}
});

ViewStateEffects

An effect that listens to the actions and updates the view state of the action.

List of effects:

  • startLoading$ - upsert the view state of the action to LOADING.
  • reset$ - resets many view state actions to IDLE.
  • error$ - upsert many view state actions to ERROR.

reset$ and error$ effects reset or error multiple view states because one action can be used in many configuration and change the view state of multiple actions.

ViewStatus

A union type that represents the view state:

export interface ViewIdle {
  readonly type: ViewStatusEnum.IDLE;
}

export interface ViewLoading {
  readonly type: ViewStatusEnum.LOADING;
}

export interface ViewLoaded {
  readonly type: ViewStatusEnum.LOADED;
}

export interface ViewError<E = unknown> {
  readonly type: ViewStatusEnum.ERROR;
  readonly error?: E;
}


export type ViewStatus<E = unknown> = ViewIdle 
| ViewLoading 
| ViewLoaded 
| ViewError<E>;

factory functions:

  • idleViewStatus - returns the idle view status.
  • loadingViewStatus - returns the loading view status.
  • loadedViewStatus - returns the loaded view status.
  • errorViewStatus - returns the error view status with an optional error payload.

ViewStateDirective

A structural directive that handles the view state of the component.

is compatible with the ComponentViewModel and ViewStatus interfaces.

Handles view status in the following way:

private viewStatusHandlers: ViewStatusHandlers<ViewStatus, T> = {
    [ViewStatusEnum.IDLE]: () => {
      this.createContent();
    },
    [ViewStatusEnum.LOADING]: () => {
      this.createSpinner();
    },
    [ViewStatusEnum.LOADED]: () => {
      this.createContent();
    },
    [ViewStatusEnum.ERROR]: ({ viewStatus }) => {
      this.createErrorState(viewStatus.error);
    },
  };

When using the AsyncPipe, the directive will render the spinner for the first time

    if (value == null) {
      this.viewContainerRef.clear();
      this.createSpinner();
      return;
    }

provideLoadingStateComponent

A utility functions that provides a custom loading component for the ViewStateDirective directive.

import { provideLoadingStateComponent } from 'ngx-view-state';

export const appConfig: ApplicationConfig = {
    providers: [
            // ...
            provideLoadingStateComponent(LoadingComponent),
    ]
};

provideErrorStateComponent

A utility functions that provides a custom error component for the ViewStateDirective directive.

import { provideErrorStateComponent } from 'ngx-view-state';

export const appConfig: ApplicationConfig = {
    providers: [
            // ...
            provideErrorStateComponent(ErrorComponent)
    ]
};

ViewStateErrorProps

An interface to implement the error state component.


@Component({
  selector: 'ngx-error-state',
  standalone: true,
  imports: [],
  template: `
    <h2>{{ viewStateError || 'There is an error displaying this data' }}</h2>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ErrorStateComponent implements ViewStateErrorComponent<string> {
  @Input() public viewStateError?: string;
}

ComponentViewModel

A generic interface that represents the view model of the component. Is used to handle the view state of the HTTP request along with mapToViewModel rxjs operator function.

import { ViewLoaded, ViewStatus } from './view-status.model';

export type ComponentViewModel<T, E = unknown> = 
{ data?: T; viewStatus: Exclude<ViewStatus<E>, ViewLoaded> } 
| { data: T, viewStatus: ViewLoaded };

mapToViewModel

A utility function that maps the response of an HTTP request to a ComponentViewModel interface. Accepts an object with onSuccess and onError handlers.

import { mapToViewModel } from 'ngx-view-state';

@Injectable()
export class TodosService {
    constructor(private http: HttpClient) {}

    loadTodos(): Observable<ComponentViewModel<Todo[]>> {
        return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos').pipe(
            mapToViewModel()
        );
    }
}