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

@rx-mind/entity-component-store

v14.0.0

Published

Component Store with Entity Selectors and Updaters

Downloads

932

Readme

@rx-mind/entity-component-store

MIT License NPM CI Status

Component Store with Entity Selectors and Updaters

Contents

Installation

  • NPM: npm i @rx-mind/entity-component-store
  • Yarn: yarn add @rx-mind/entity-component-store

Note: @rx-mind/entity-component-store has @ngrx/component-store as a peer dependency.

Entity State

The state of EntityComponentStore is defined by extending EntityState:

import { EntityState } from '@rx-mind/entity-component-store';

interface ProductsState extends EntityState<Product, number> {
  selectedId: number | null;
}

EntityState accepts the entity type as the first, and the id type as the second generic argument. However, the second argument is optional and if not provided, the id type will be string | number.

To create the initial state, this package provides getInitialEntityState function. It accepts the initial values of additional state properties as the input argument.

import { getInitialEntityState } from '@rx-mind/entity-component-store';

const initialState = getInitialEntityState<ProductsState>({ selectedId: null });

If the state doesn't contain additional properties, then the input argument should not be passed to getInitialEntityState:

import { getInitialEntityState } from '@rx-mind/entity-component-store';

type ProductsState = EntityState<Product, number>;

const initialState = getInitialEntityState<ProductsState>();

Initialization

The constructor of EntityComponentStore accepts a configuration object that contains three optional properties: initialState, selectId and sortComparer.

import { EntityComponentStore } from '@rx-mind/entity-component-store';

@Injectable()
export class ProductsStore extends EntityComponentStore<ProductsState> {
  constructor() {
    super({ initialState, selectId, sortComparer });
  }
}

selectId should be provided when the entity identifier name is not equal to id:

import { SelectId } from '@rx-mind/entity-component-store';

interface Product {
  key: number;
  name: string;
  price: number;
}

const selectId: SelectId<Product, number> = (product) => product.key;

sortComparer is a function used to sort the collection. If not provided, entity collection will be unsorted which is more performant.

import { SortComparer } from '@rx-mind/entity-component-store';

const sortComparer: SortComparer<Product> = (p1, p2) => p1.name.localeCompare(p2.name);

Similar to ComponentStore, the state of EntityComponentStore can be initialized lazily by calling setState method:

@Injectable()
export class ProductsStore extends EntityComponentStore<ProductsState> {
  constructor(private readonly productsService: ProductsService) {
    super();
  }
}

@Component({
  selector: 'rx-mind-products',
  templateUrl: './products.component.html',
  viewProviders: [ProductsStore],
})
export class ProductsComponent implements OnInit {
  constructor(private readonly productsStore: ProductsStore) {}

  ngOnInit(): void {
    this.productsStore.setState({ entities: {}, ids: [] });
  }
}

Also, there is an option to provide the EntityComponentStore configuration via ENTITY_COMPONENT_STORE_CONFIG injection token:

import {
  EntityComponentStore,
  ENTITY_COMPONENT_STORE_CONFIG,
  EntityState,
  getInitialEntityState,
} from '@rx-mind/entity-component-store';

type ProductsState = EntityState<Product, number>;

const initialState = getInitialEntityState<ProductsState>();

@Component({
  selector: 'rx-mind-products',
  templateUrl: './products.component.html',
  viewProviders: [
    { provide: ENTITY_COMPONENT_STORE_CONFIG, useValue: { initialState } },
    EntityComponentStore,
  ],
})
export class ProductsComponent {
  constructor(private readonly productsStore: EntityComponentStore<ProductsState>) {}
}

Selectors

EntityComponentStore provides following selectors:

  • ids$ - Selects the array of entity ids.
  • entities$ - Selects the entity dictionary.
  • all$ - Selects the array of all entities.
  • total$ - Selects the total number of entities.

Usage:

@Injectable()
export class ProductsStore extends EntityComponentStore<ProductsState> {
  private readonly selectedId$ = this.select((s) => s.selectedId);

  readonly vm$ = this.select(
    this.all$,
    this.entities$,
    this.total$,
    this.selectedId$,
    (products, productDictionary, totalProducts, selectedId) => ({
      products,
      selectedProduct: selectedId !== null ? productDictionary[selectedId] : null,
      totalProducts,
    })
  );

  constructor() {
    super({ initialState });
  }
}

Updaters

EntityComponentStore provides following updaters:

  • addOne - Adds one entity to the collection.
  • addMany - Adds multiple entities to the collection.
  • setOne - Adds or replaces one entity in the collection.
  • setMany - Adds or replaces multiple entities in the collection.
  • setAll - Replaces current collection with the provided collection.
  • removeOne - Removes one entity from the collection.
  • removeMany - Removes multiple entities from the collection by ids or by predicate.
  • removeAll - Clears entity collection.
  • updateOne - Updates one entity in the collection. Supports partial updates.
  • updateMany - Updates multiple entities in the collection. Supports partial updates.
  • upsertOne - Adds or updates one entity in the collection. Supports partial updates.
  • upsertMany - Adds or updates multiple entities in the collection. Supports partial updates.
  • mapOne - Updates one entity in the collection by defining a map function.
  • map - Updates multiple entities in the collection by defining a map function.

Each entity updater accepts a partial state, or a partial updater function as an optional second argument.

Usage:

@Component({
  selector: 'rx-mind-products',
  templateUrl: './products.component.html',
  viewProviders: [ProductsStore],
})
export class ProductsComponent {
  constructor(private readonly productsStore: ProductsStore) {}

  onUpdateProduct(productUpdate: Update<Product, number>): void {
    this.productsStore.updateOne(productUpdate);
  }

  onAddProduct(product: Product): void {
    this.productsStore.addOne(product, { selectedId: product.id });
  }

  onRemoveProduct(id: number): void {
    this.productsStore.removeOne(id, ({ selectedId }) => ({
      selectedId: selectedId === id ? null : selectedId,
    }));
  }
}