Created
January 9, 2018 17:41
-
-
Save jugyo/3cfdf7fe58187c50e5cfb65721664fc6 to your computer and use it in GitHub Desktop.
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, { Component } from 'react'; | |
import { observer } from 'mobx-react'; | |
import mobx from 'mobx'; | |
import Button from 'material-ui/Button'; | |
import { LinearProgress } from 'material-ui/Progress'; | |
import Api from '../Api' | |
// Strict mode enforces that all state modifications are done by an action. | |
mobx.useStrict(true); | |
/** | |
* Usage: | |
* | |
* <MobxExample store={store}/> | |
*/ | |
class MobxExample extends Component { | |
handleClick = () => { | |
this.props.store.fetchUsers() | |
} | |
render() { | |
const { store } = this.props | |
console.log(store.apiState); | |
return ( | |
<div> | |
<div> | |
{ store.apiState === "pending" && | |
<LinearProgress/>} | |
</div> | |
<h1>MobxExample</h1> | |
<div> | |
<Button raised onClick={this.handleClick}>Fetch Users</Button> | |
</div> | |
<ul> | |
{ store.users.map((user) => { | |
return <li key={user.id}>{user.name}</li> | |
})} | |
</ul> | |
</div> | |
); | |
} | |
} | |
// To observe a mobx.observable | |
export default observer(MobxExample); | |
// This will be inject to MobxExample component as a prop | |
export const store = mobx.observable({ | |
apiState: "done", // "pending" / "done" / "error" | |
users: [], | |
fetchUsers: mobx.action('fetchUsers', function (user) { | |
this.apiState = "pending" | |
Api.get('/example').then((response) => { | |
console.log(response.data); | |
mobx.runInAction(() => { | |
this.users = response.data.users | |
this.apiState = "done" | |
}) | |
}).catch((error) => { | |
mobx.runInAction(() => { | |
this.apiState = "done" | |
}) | |
this.setApiState("error") | |
}) | |
}), | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment