Implementation of store injection to react component with mobx, typescript and decorator metadata
npm i --save mobx-react-inject reflect-metadata
//tsconfig.json
{
"compilerOptions": {
//...
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
//...
}
}
//your-main-index.ts
import "reflect-metadata"
import {StoreProvider} from "mobx-react-inject"
class App extends React.Component<{}, void> {
render() {
return <StoreProvider>
...
</StoreProvider>
}
}
class MyStore {
public hello() {
return "Hello"
}
}
// ----
import {inject} from "mobx-react-inject"
class MyComponent extends React.Component<{}, void> {
@inject
private myStore: MyStore
render() {
return <span>{this.myStore.hello()}</span>
}
}
class MyStoreDep {
public word() {
return "word"
}
}
class MyStore {
constructor(@inject private myStoreDep: MyStoreDep)
public hello() {
return `Hello ${this.myStoreDep.word()}`
}
}
import {StoreConstructor, StoreInstance} from "mobx-react-inject"
class App extends React.Component<{}, void> {
private stores: Map<StoreConstructor, StoreInstance>
componentWillMount() {
this.stores = new Map([
[MyStore, new MyStore()]
])
}
render() {
return <StoreProvider stores={this.stores}>
<StoreProvider>
...
</StoreProvider>
</StoreProvider>
}
}