@strategies/portals
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

Sasaki's Stores

Register stores in a flat structure to be referenced anywhere in your React app.

Install

yarn add @strategies/stores react mobx

Example

App Code

import { computed } from 'mobx';
import { register, Store, stores } from '@strategies/stores';

class AppStore extends Store {

    /**
    * onRegister is a "secondary constructor" that fires when you register
    * this store, as seen below.
    */
    onRegister() {
        const { ui } = stores;
        console.log(ui.id); // -> 5
    }

    /**
    * onUpdateRegistration runs if `register` is called again after this 
    * store has already been registered.
    */
    onUpdateRegistration(stores: {[key: string]: Store}) {
        if (stores.layout) {
            console.log('We now have the layout store');
        }
    }

    /**
    * `stores` is a MobX observable meaning that we can observe
    * changes made to the store registry.
    */
    @computed
    get width() {
        return stores.layout.width;
    }

}

class UiStore extends Store {

    id: string;

    constructor(id: string) {
        super();
        this.id = id;
    }

}

class LayoutStore extends Store {

    readonly width: number = 500;

}


register({
    app: new AppStore(),
    ui: new UiStore('5'),
});

// We can register new stores at any point. Useful for enforcing load order.
register({
    layout: new LayoutStore()
});

React

import { observer } from 'mobx-react';
import { useStores } from '@strategies/stores';

/**
* the `useStores` hook is used to inject the stores
* into our React components
*/
export default observer(function App() {
    const { app } = useStores();

    return (
        <div className="App" style={{ width: `${app.width}px` }}>
            {/* ... */}
        </div>
    )
});

Readme

Keywords

none

Package Sidebar

Install

npm i @strategies/portals

Weekly Downloads

0

Version

0.1.4

License

MIT

Unpacked Size

35.2 kB

Total Files

7

Last publish

Collaborators

  • scottdpenman
  • tadiraman
  • sasaki-dev
  • arminakvn
  • eyoungberg
  • sasaki-strategies