Code Monkey home page Code Monkey logo

stateful's Introduction

Build Status Coverage Status npm version

What is Stateful?

Stateful is a tiny state manager for TypeScript and RxJS projects. It's a class that encapsulates a BehaviorSubject and provides basic store manipulation methods. It's indented for use in small classes that don't need the complexity of a larger state manager.

Stateful is about 1kb in size after minification.

Installation

To get started, install the package from npm.

npm install --save @reactgular/stateful

Usage

Stateful is small, simple and easy to use.

  • You construct a Stateful object with a default state and use an interface to define the state object type.
  • You can then patch(), set() and reset() the internal state.
  • You use select() to create observables of state property changes, and selector() to create custom selectors.
import {Stateful} from '@reactgular/stateful';

interface ExampleState {name: string; count: number; }
const state = new Stateful<ExampleState>({name: "Example", count: 4});
state.patch({name: 'Something'});
state.select('name').subscribe(value => console.log(value)); // prints "Something"

Stateful Class

Usage documentation for the Stateful<TState> class.

Properties

  • state$: An observable that emits all changes to the state.

Methods

  • complete(): Stops emitting changes made to the state.
  • default(): Returns the default state used with the constructor or reset.
  • patch(state: Partial<TState>): Patches the current state with partial values.
  • patch<TKey extends keyof TState>(name: TKey, value: TState[TKey]): Patches a single property on the state with a value.
  • reset(defaultState?: TState): Resets the state to the original state used by the constructor, or updates the original state with the passed argument.
  • select<TKey extends keyof TState>(name: TKey): Observable<TState[TKey]>: Creates an observable that emits values from a property on the state object.
  • selector<TValue>(selector: (s: TState) => TValue): Observable<TValue>: Creates an observable that emits values produced by the selector function.
  • set(state: TState): Sets the current state.
  • snapshot(): TState: Peeks at the current internal state.

Examples

You can create selectors from the state by using property names. TypeScript will infer the correct Observable<Type> from the property key.

import {Stateful} from '@reactgular/stateful';

interface ExampleState {name: string; count: number; }
const state = new Stateful<ExampleState>({name: "Example", count: 4});

const name$ = state.select('name'); // Observable<string>
name$.subscribe(value => console.log(value)); // prints "Example", "Hello World"

state.patch({name: "Hello World"});

You can write your own custom selectors.

import {Stateful} from '@reactgular/stateful';

interface ExampleState {name: string; count: number; }
const state = new Stateful<ExampleState>({name: "Example", count: 4});

const nameAndCount$ = state.selector(state => `${state.name} AND ${state.count}`);
nameAndCount$.subscribe(value => console.log(value)); // prints "Example AND 4"

Example Angular Service

You can use Stateful as a base class for an Angular service.

import {Observable} from 'rxjs'; 
import {Stateful} from '@reactgular/stateful';

interface ExampleState { counter: number }

@Injectable()
export class ExampleService extends Stateful<ExampleState> {
    public constructor() {
        super({counter: 0})
    }
 
    public counter(): Observable<number> {
        return this.select('counter');
    }

    public increment() {
        const counter = this.snapshot().counter + 1;
        this.patch({counter});
    }

    public decrement() {
        const counter = this.snapshot().counter - 1;
        this.patch({counter});
    }
}

Example Angular Component

You can use Stateful as an internal state manager for an Angular component. By patching incoming @Input() properties into the Stateful object you can more easily work with observables.

interface ProductState {
    productId?: number;
    price?: number;
}

@Component({
    selector: 'project',
    template: `<span>Price: {{price$ | async}}</span>
               <span>Taxes: {{taxes$ | async}}</span>`
})
export class ProductComponent implements OnInit {
    private state: Stateful<ProductState> = new Stateful<ProductState>({});

    public price$ = this.state.select('price');

    public taxes$ = this.state.select('price').pipe(
        map(price => price * 0.07)    
    );

    @Input()
    public set productId(productId: string) {
        this.state.patch({productId});    
    }
  
    @Input()
    public set price(price: string) {
        this.state.patch({price});    
    }
}

StorageStateful Class

StorageStateful extends Stateful and offers persistence of state to a storage service like localStorage or sessionStorage.

import {StorageStateful} from '@reactgular/stateful';

interface ExampleState {name: string; count: number; }
const state = new StorageStateful<ExampleState>('app', {name: "Example", count: 4});

Pass the storage key as the first parameter to the constructor, and the default state as the second parameter. The state will be persisted to localStorage by default under that key. Any changes patched to the state are serialized to storage.

You can configure custom serializers and storage objects using the StorageStatefulConfig<TState extends {}> interface as the third parameter.

/**
 * Configuration options for the StorageStateful class.
 */
export interface StorageStatefulConfig<TState extends {}> {
    /**
     * A deserialize function that converts a string into a state object.
     */
    deserializer?: (state: string) => TState;

    /**
     * A serialize function that converts a state object into a string.
     */
    serializer?: (state: TState) => string;

    /**
     * The storage object to use (can be localStorage or sessionStorage).
     */
    storage?: Storage;
}

stateful's People

Contributors

codemile avatar dependabot[bot] avatar

Stargazers

 avatar

Watchers

 avatar

Forkers

canvasgfx

stateful's Issues

Add extensions for patching.

Update the patch method to support different ways of being called.

patch(key: string, value: any);

Patches a specific property (using keyof).

patch(cb: (state) => state);

Patches the state using a callback that receives the snapshot as a parameter.

These are the general ideas. It can be implemented differently if needed. Maybe overloading the same function name isn't ideal.

Update default state when calling reset()

reset() current restores the state to the original state value. Add an optional parameter to reset with a new default value.

It's basically the same as calling set() except that this will update what value reset() uses when called without an argument.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.