0.0.1 • Published 5 years ago
use-mobx-store v0.0.1
use-mobx-store
The missing use-store (or use-observable) hook for MobX and MobX-React.
It allows you to subscribe to MobX store without using mobx-react's observer High Order Component.
Warning:
This hook is highly experimental, although fun, it might be dangerous to use it in production :(
Installation:
npm install use-mobx-store
.
Usage
Render provider in Application's root
import React from 'react';
import { UseStoreProvider } from 'use-mobx-store';
import { Button } from './Button';
import logo from './logo.svg';
export const App = () => {
return (
<UseStoreProvider>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Button />
</header>
</div>
</UseStoreProvider>
);
};
Create a store (or two)
src/stores/count-store.tsx
import { RegisterStore } from 'use-mobx-store';
import { observable } from 'mobx';
@RegisterStore()
export class CountStore {
@observable
pressCount = 0;
increaseCounter = () => {
this.pressCount += 1;
};
}
src/stores/button-store.tsx
import { RegisterStore, InjectStore } from 'use-mobx-store';
import { CountStore } from './count-store';
@RegisterStore()
export class ButtonStore {
@InjectStore(CountStore)
private countStore: CountStore;
handlePress = () => {
this.countStore.increaseCounter();
};
}
Using a store turns your component into a observer
import React from 'react';
import { CountStore } from './stores/count-store';
import { useStore } from 'use-mobx-store';
import { ButtonStore } from './stores/button-store';
export const Button = () => {
const countStore = useStore(CountStore);
const buttonStore = useStore(ButtonStore);
return <button onClick={countStore.increaseCounter}>I have been pressed {buttonStore.handlePress} times</button>;
};
0.0.1
5 years ago