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

@jeiraon/state-holder

v1.1.6

Published

mini store like using RxJs

Downloads

10

Readme

State Holder

state holder is a "mini store like" using RxJs

Install

npm install @jeiraon/state-holder

rxjs is set as a peerDependencies to avoid conflict with your main project. In most use case, you should already have it installed so it will use the same version. Otherwise, you can install it.

npm install rxjs@^6.6.0

Configuration

You can turn on the action logs by using

stateHolderConfig.logger = false; // default false
stateHolderConfig.allowDistinctToPass = false; // default false
stateHolderConfig.allowNullableToPass = false; // default false

Each time an action is dispatched, you will be able to see the logs in your browser's console in the following form { action, state }

Example

Basic

Creating a new basic state holder

// structure of the state
interface SampleState {
    text: string;
}
// init state (when instantiating the class)
const initSampleState: SampleState = {
    text: '',
}
// create an action
const setTextAction = createAction(
        'Set text',
        (state: SampleState, { text }: { text: string }): SampleState => ({ ...state, text })
);
// create a selector
const textSelector = createSelector((state: SampleState): string => state.text);
// instiate a new basic state holder
const state = createBasicState(initSampleState);
// dispatch and select example
state.dispatch(setTextAction, { text: 'sample' });
state.select$(textSelector).subscribe({next: (v) => console.log(v)})

Using the state holder anywhere you need to change or select a specific state

// dispatch and select example
state.dispatch(setTextAction, { text: 'sample' });
state.select$(textSelector).subscribe({next: (v) => console.log(v)})

Using angular Service for more complexe behaviours

// structure of the state
interface ProductState {
    products: string[];
}
// init state (when instantiating the class)
const initProductState: ProductState = {
    products: [],
};
// create an action
const addProductAction = createAction(
        'Add product',
        (state: ProductState, { product }: { product: string }): ProductState => ({
            ...state,
            products: [
                ...state.products,
                product
            ]
        })
);
// create a selector
const productSelector = createSelector((state: ProductState): string[] => state.products);

In a service

@Injectable({
  providedIn: 'root',
})
class ProductService extends StateHolder<ProductState> {
    constructor(http: HttpClient){
        super(initProductState);
    }

    public getProductById(id: string): void {
        this.http.get<string>(`localhost:3000/product/${id}`)
            .pipe(take(1))
            .subscribe((product:string) => {
                this.dispatch(addProductAction, { product });
            })
    }
}

In a component

@Component({
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss']
})
export class ProductListComponent implements OnInit {
    // use `async` pipe in html to subscribe to it and use the data
    public products$: Observable<string[]> = this.productService.select$(productSelector);

    constructor(public productService: ProductService) {}

    ngOnInit(): void {}
}

Parameterized Selector

// Primitive (number, string)
const selectSample = createSelector((state: SampleState, id: number) => state.samples[id]);
state.select$(selectSample, 0).subscribe({ next: s => console.log(s) });

// Array
const selectSamples = createSelector((state: SampleState, ids: number[]) => {
    const samples = [];
    for (const id of ids) {
        samples.push(state.samples[id]);
    }
    return samples;
});

state.select$(selectSamples, [0, 2]).subscribe({ next: s => console.log(s)});

// Object
const selectSamples = createSelector((state: SampleState, { id, key }: { id: number, key: string }) => {
    return {
        id: state.samples[id],
        key: state.dict[key]
    };
});

state.select$(selectSamples, { id: 0, key: 'first' }).subscribe({next: s => console.log(s)});

Dependency

rxjs: ^6.6.0

Note

I like to extend my Angular services with the state-holder when I do need a big Store like NgRx in my app.

CommonJS is not supported., This module has been build for ESNext

Todo

  • [x] : Basic implementation
  • [x] : Arguments to selector (eg: to get by id)
  • [ ] : Add utilitaries functions to help when selecting or disptaching actions
  • [ ] : ...