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

@tomalaforge/ngrx-callstate-store

v0.0.4

Published

Enhance NgRx component-store by providing a loading/error state

Downloads

3

Readme

NgRx CallState ComponentStore

NgRx CallState ComponentStore is a small library that extends the @Ngrx/component-store by adding a loading and error state to your custom state.

Installation

Requires @Ngrx/component-store

Yarn:

yarn add @tomalaforge/ngrx-callstate-store

NPM:

npm i @tomalaforge/ngrx-callstate-store

Introduction

When making XHR calls or any asynschronous tasks, you always need a loading or error state. By using CallStateComponentStore, you can easily manage the loading and error states of your async tasks, which makes your code more organized and maintainable.

Example

@Injectable()
export class AppStore extends CallStateComponentStore<{todos: Todo[]}> {
  readonly todos$ = this.select((state) => state.todos);

  readonly vm$ = this.select({
    todos: this.todos$,
    loading: this.loading$,
  }, {debounce: true});

  constructor(private todoService: TodoService) {
    super({ todos: [] });
  }

  readonly fetchTodo = this.effect<void>(
    pipe(
      tap(() => this.startLoading()),
      switchMap(() =>
        this.todoService.getAllTodo().pipe(
          tapResponse(
            (todos) => this.stopLoading({ todos }),
            (error: unknown) => this.handleError(error, {todos: []})
          )
        )
      )
    )
  );

By extending your class with CallStateComponentStore, a CallState property is added to your state.

You don't need to provide a state if you only want to use the CallState property.

export type LoadingState = 'INIT' | 'LOADING' | 'LOADED';

export interface ErrorState {
  error: CustomError;
}

export type CallState = LoadingState | ErrorState;

You can override CustomError as needed.

API

initialization

setInitState

The setInitState method lets you initialize your custom state if you are not using the constructor.

setInitState = (state: T): void

updater

startLoading

The startLoading method sets the CallState property to the LOADING state. You can pass optional state properties if you want to patch your own state.

startLoading = (state: Optional<T>): void
stopLoading

The stopLoading method sets the CallState to the LOADED state. You can pass an optional state properties as well.

stopLoading = (state: Optional<T>): void
updateCallState

The updateCallState method updates the callState with the inputed value.

updateCallState = (callState: CallState): void
handleError

The handleError method handles errors. You can pass an optional state.

handleError = (error: unknown, state: Optional<T>): void

selector

isLoading$

isLoading$ return a boolean, true if state is loading, false otherwise

isLoadingWithFlicker$

isLoadingWithFlicker$ return the same as isLoading$ but with a small delay. This can be useful when you don't want your page to flicker.

isLoaded$

isLoaded$ return a boolean, true if state is loaded, false otherwise

callState$

isLoading$ return the CallState

error$

isLoading$ return your error message using the getErrorMessage of your ErrorState. (see below)


Customize the library

ErrorState

You can provide your own implementation of The ErrorState by implementing ErrorHandler

export interface ErrorHandler<T extends CustomError> {
  toError: (error: unknown) => T;
  getErrorMessage: (error?: T) => string | undefined;
}

The toError method converts the error input into the desired error object. The getErrorMessage method returns the well-formed error message that you want to display to your user.

The current implementation is as follow:

export const UNKNOWN_ERROR_CAUSE = 'UNKNOWN_ERROR';
export const UNKNOWN_ERROR_MESSAGE = 'unknown error occured';

export class CallStateError {
  name: string;
  message: string;
  stack?: string;

  constructor(name = '', message = '') {
    this.name = name;
    this.message = message;
  }
}

export class CallStateErrorHandler implements ErrorHandler<CallStateError> {
  toError = (error: unknown): CallStateError => {
    if (error instanceof CallStateError) return error;
    if (error instanceof Error)
      return new CallStateError(error.name, error.message);
    return new CallStateError(UNKNOWN_ERROR_CAUSE, UNKNOWN_ERROR_MESSAGE);
  };

  getErrorMessage = (error?: CallStateError): string | undefined => {
    return error?.message;
  };
}

Let's say you want to customize it as follow:

export const UNKNOWN_ERROR_MESSAGE = 'unknown error occured';

export class MyError {
  message: string;
  code: number

  constructor(message = '', code = 404) {
    this.message = message;
    this.code = code;
  }
}

export class MyErrorHandler implements ErrorHandler<MyError> {
  toError = (error: unknown): MyError => {
    if (error instanceof MyError) return error;
    if (error instanceof Error)
      return new MyError(error.message);
    return new MyError(UNKNOWN_ERROR_MESSAGE);
  };

  getErrorMessage = (error?: MyError): string | undefined => {
    return error.code error?.message;
  };
}

Now to override the default implementation, you need to provide it as follow :

provideErrorHandler(MyErrorHandler);

You can provide it at root level to apply it to your whole application or at the component level for more specific implementation.

Flicker Delay

The default delay is 300ms but you can override it by providing it as follow:

provideFlickerDelay(500);