Skip to content

Instantly share code, notes, and snippets.

@jugyo
Created January 9, 2018 17:41
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 jugyo/3cfdf7fe58187c50e5cfb65721664fc6 to your computer and use it in GitHub Desktop.
Save jugyo/3cfdf7fe58187c50e5cfb65721664fc6 to your computer and use it in GitHub Desktop.
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