Skip to content

Instantly share code, notes, and snippets.

@jorilallo
Created November 23, 2017 00:03
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 jorilallo/871c780a9702073e448a72063e13214c to your computer and use it in GitHub Desktop.
Save jorilallo/871c780a9702073e448a72063e13214c to your computer and use it in GitHub Desktop.
MobX React example
import React from 'react';
import { observable, computed, action } from 'mobx';
import { observer } from 'mobx-react';
class UserStore {
@observable firstName;
@observable lastName;
@observable isLoading = false;
@observable error;
@computed
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
@action
fetchUserData = async () => {
this.isLoading = true;
try {
const res = await fetch('/api/user');
const data = await res.json();
this.firstName = data.firstName;
this.lastName = data.lastName;
} catch (e) {
this.error = e.message;
}
this.isLoading = false;
};
}
@observer
class UserComponent extends React.Component {
constructor(props) {
super(props);
this.store = new UserStore();
}
componentDidMount() {
this.store.fetchUserData();
}
render() {
return (
<div>
{this.store.error && (
<div>Error loading user: ({this.store.error})</div>
)}
{this.store.isLoading ? (
<div>Loading user...</div>
) : (
<div>User: {this.store.fullName}</div>
)}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment