Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Minimal mobx store app with observables
import React from "react";
import ReactDOM from "react-dom";
import { observable } from "mobx";
import { observer } from "mobx-react";
// Store
class Store {
@observable isLoading = false;
@observable users = [];
}
// API
const sleep = async ms => new Promise(resolve => setTimeout(resolve, ms));
const getData = async () => {
await sleep(2000);
return [1, 2, 3];
};
// App
@observer
class App extends React.Component {
loadData = async () => {
const { store } = this.props;
store.isLoading = true;
store.users = await getData();
store.isLoading = false;
};
render() {
const { store } = this.props;
return (
<div>
<button onClick={this.loadData}>Load</button>
{store.isLoading ?
<div>Loading...</div>
:
store.users.map(user => <div>{user}</div>)
}
</div>
);
}
}
// Running
const store = new Store();
document.addEventListener("DOMContentLoaded", () =>
ReactDOM.render(<App store={store} />, document.body)
);
import React from "react";
import ReactDOM from "react-dom";
import { observable } from "mobx";
import { observer } from "mobx-react";
class Store { @observable num = 0; }
@observer class App extends React.Component {
render() {
const { store } = this.props;
return (
<div>
<button onClick={() => store.num--}>-</button>
<button readOnly>{store.num}</button>
<button onClick={() => store.num++}>+</button>
</div>
);
}
}
const store = new Store();
document.addEventListener("DOMContentLoaded", () =>
ReactDOM.render(<App store={store} />, document.body)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment