@strategies/stores
v1.3.4
Published
We need stores, and we need them MobX, and we need them in context
Downloads
185
Keywords
Readme
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>
)
});