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

@betgames/bg-state-manager

v3.1.3

Published

React atom state manager based on hooks

Downloads

723

Readme

State manager

Motivation

Implement state manager based on atoms (small peace of states). Using recoil and jotai "from bottom to top" methodology.

Methods API

Store

Extend your custom provider

class SomeStore extends Store<number[]> {
    constructor() {
        super({
            key: 'SomeStoreKey',
            default: {
                value: 0,
                isVisible: true
            },
            persist: true,
            blacklist: ['isVisible'],
        });
    }
    // you custom methods
};

Creates a Store to be used across the entire application.

Arguments

key: string

The namespace of your store state, will be used to identify your state among other states in the app. Will be usefull for Redux DevTools.

default: State

Default value for state. Can any object "State" interface. Also will be used by reset(). Idea also to allow passing function to get initial state: () => State.

persist?: boolean

The flag, defines if the state should be persisted in the local storage

whitelist?: Array<keyof State>

List of store fields, which should be persisted. If whitelist exists, unmentioned fields will be skipped.

blacklist?: Array<keyof State>

List of store fields, which should not be persisted. Blacklist and whitelist only work one level deep.

migration?: IMigration<State>

interface IMigration<State>: {
    version: number;
    callback(cache: State): State;

Migration callback which helps to migrate from any version of stored state to the current state version. If passed version is the same as version of persisted store, the migration callback call will be skipped.

Usage

// store/GameState.ts
interface ISomeGameState {
    gameId: GameId;
    secondsLeft: number;
    state: State;
}

class SomeGameStateStore extends Store<ISomeGameState> {
    constructor() {
        super({
            key: 'GameState',
            default: null,
        });
    }
    // you custom methods
};

export const someGameStateStore = new SomeGameStateStore();

// components/SomeComponent.tsx
export const SomeComponent: React.FC = () => {
    const state = useStore(someGameStateStore);
    
    if (!state) {
        return null; // or use React.Suspense
    }

    return (
        <span>{state.secondsLeft}</span>
    );
};

Entity store

// store/GameState.store.ts
interface IGameState {
    secondsLeft: number;
    state: State;
}

class GameStateEntity extends Entity<GameId, IGameState> {
    constructor() {
        super({
            key: 'GameState',
            default: null,
        });
    }
    // you custom methods
};

export const gameStateEntity = new GameStateEntity();

// components/SomeComponent.tsx
export const SomeComponent: React.FC = () => {
    const state = useStore(gameStateEntity.store(GameId.SomeGame));

    if (!state) {
        return null; // or use React.Suspense 
    }

    return (
        <span>{state.secondsLeft}</span>
    );
};

Create a store entity. Siblings of states which separated by primitive Parameter.

Arguments

Same arguments as Store, additional requires generic parameter type Primitive = number | string;

Usage

// store/GameState.entityts
interface IGameState {
    gameId: GameId;
    secondsLeft: number;
    state: State;
}

IStoreInterface

Hooks / components starts to consume store derived state. Return derived state of the store with selector.

update: SetterOrUpdaterImmer<State>

A method which can update state. Supports both setter and update behaviours. Under the hood works with Immer.

Store.update(newState);
Store.update((draft) => {
    draft.someKey = someNewValue;
});

reset(): void

A method which resets a store to it default state value.

value: State

A getter that returns the store's current state.

subscribe(subscriber: Subscriber<State>): () => void

A method to subscribe to the store state, can be used outside of the react. Return unsubscribe function.

unsubscribe(subscriber: Subscriber<State>): void

A method to unsubscribe from the store state updates.

useStore with multiple stores

Hooks can be used with multiple stores Recommendation to use reselect for declaring selectors https://github.com/reduxjs/reselect#q-can-i-use-reselect-without-redux. Reselect will memoize result and Object.is will not allow re-rendering of component with the same reference Can accept up to 5 different stores, if you need more, please add more functions overloads in types.d.ts file and create PR In practice you can have as many stores as you wish as a dependency

interface IStoreA {
    test: number;
    multiplier: number;
}

interface IStoreB {
    list: number[];
    count: number;
}

class StoreA extends Provider<IStoreA> {}
class StoreB extends Provider<IStoreB> {}

const storeA = new StoreA({
    key: 'storeA',
    default: {
        test: 0,
        multiplier: 3,
    },
});

const storeB = new StoreB({
    key: 'storeB',
    default: {
        list: [],
        count: 0,
    },
});

// createSelector from "reselect"  library
// result function will trigger only if multiplier or list has changed
const mySelector = createSelector(
    [
        (storeAState: IProviderA) => storeAState.multiplier,
        (storeBState: IProviderB) => storeBState.list,
    ],
    (multiplier, list) => list.map((value) => value * multiplier),
);

const someCombinedState = useStore([storeA, storeB], mySelector);