-
-
Save jorilallo/871c780a9702073e448a72063e13214c to your computer and use it in GitHub Desktop.
MobX React example
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 { 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