More Related Content More from Lucas Lira Gomes More from Lucas Lira Gomes (7) Mobx2. Software Engineer
Passionate Hacker
ArchLinux Zealot
FOSS Enthusiast
I’m fond of doing
things that last
and all that jazz.
Lucas Lira Gomes
2
contact@x8lucas8x.com
linkedin.com/in/x8lucas8x
facebook.com/x8lucas8x
youtube.com/X80lucas08X
twitter.com/x8lucas8x
x8lucas8x.com
github.com/x8lucas8x
6. @observable
import { observable } from "mobx";
class OrderLine {
@observable price = 0;
@observable amount = 1;
}
const orderLineStore = new OrderLine();
export default orderLineStore;
7. @computed
import { observable, computed } from "mobx";
class OrderLine {
@observable price = 0;
@observable amount = 1;
@computed get total() {
return this.price * this.amount;
}
}
const orderLineStore = new OrderLine();
export default orderLineStore;
8. @action
import { observable, action } from "mobx";
class OrderLine {
@observable price = 0;
@observable amount = 1;
@action getPrice() {
fetch(
"www.orderline.com/api/price"
).then(this.getPriceReceive);
}
@action getPriceReceive(response) {
this.price = response.json().price;
}
}
...
9. reaction
import {reaction, autorun, when} from "mobx";
const reaction1 = reaction(
() => orderLine.total,
total => console.log("reaction 1:", total)
);
const autorun1 = autorun(
() => console.log(
"autorun 1:", orderLine.total
)
);
const when1 = when(
() => orderLine.total > 1,
() => console.log("when 1: true")
);
10. @observer
import { observer } from "mobx-react";
@observer
class Total extends React.Component {
render() {
const { orderLineStore } = this.props;
return (
<span>
{orderLineStore.total}
</span>
);
}
};
12. Pros x Cons
● Pros
○ Open Source
○ Familiar
○ Less code
○ No thunks and ...
○ Interoperability
○ Active community
● Cons
○ DevTools
○ Tracking access
implications
14. Store Injection
import { Provider } from "mobx-react";
…
ReactDOM.render(
...
<Provider stores={allStores}>
<App />
</Provider>
...,
document.getElementById('root')
);
import { observer, inject } from "mobx-react";
@inject("stores")
@observer
class ContactFormPage extends Component {
…
// accessing store via props
const { contactStore } = this.props.stores;
return (
<ContactForm
store={contactStore}
form={this.form}
contact={contactStore.entity}
/>
)
…
}
15. Root Store
import { observer } from "mobx-react";
class RootStore {
constructor() {
this.userStore = new UserStore(this);
}
}
class TodoStore {
@observable todos = []
constructor(rootStore) {
this.rootStore = rootStore;
}
}
...
17. Mobx DEV Tools
import DevTools from "mobx-react-devtools";
class MyApp extends React.Component {
render() {
return (
<div>
...
<DevTools />
</div>
);
}
}