Skip to content

Instantly share code, notes, and snippets.

@mweststrate
Last active September 13, 2020 08:08
Show Gist options
  • Save mweststrate/e0d7dd9bb0d410b08c35 to your computer and use it in GitHub Desktop.
Save mweststrate/e0d7dd9bb0d410b08c35 to your computer and use it in GitHub Desktop.
mobx-example
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/
@ronaldborman
Copy link

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.

@johndgiese
Copy link

I don't know mobx very well, but I think @ronaldborman is correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment