Last active
November 9, 2018 13:30
-
-
Save andrienko/45e15dd5d9b3b6b94391a2f5b534ee38 to your computer and use it in GitHub Desktop.
Minimal mobx store app with observables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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