Last active
September 13, 2020 08:08
-
-
Save mweststrate/e0d7dd9bb0d410b08c35 to your computer and use it in GitHub Desktop.
mobx-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
class Person { | |
@observable firstName = "Michel"; | |
@observable lastName = "Weststrate"; | |
@observable nickName; | |
@computed get fullName() { | |
return this.firstName + " " + this.lastName; | |
} | |
} | |
const michel = new Person(); | |
// Reaction: log the profile info whenever it changes | |
autorun(() => console.log(person.nickName ? person.nickName : person.fullName)); | |
// Example React component that observes state | |
const profileView = observer(props => { | |
if (props.person.nickName) | |
return <div>{props.person.nickName}</div> | |
else | |
return <div>{props.person.fullName}</div> | |
}); | |
// Action: | |
setTimeout(() => michel.nickName = "mweststrate", 5000) | |
React.render(React.createElement(profileView, { person: michel }), document.body); | |
// This snippet is runnable in jsfiddle: https://jsfiddle.net/mweststrate/049r6jox/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't line 14 be something like
autorun(() => console.log(michel.nickName ? michel.nickName : michel.fullName));
? AFAICS there is no person variable in the scope of the callback function.