Skip to content

Instantly share code, notes, and snippets.

@andrienko
Last active November 9, 2018 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrienko/45e15dd5d9b3b6b94391a2f5b534ee38 to your computer and use it in GitHub Desktop.
Save andrienko/45e15dd5d9b3b6b94391a2f5b534ee38 to your computer and use it in GitHub Desktop.
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