Mobx - jellyfish-tom/TIL GitHub Wiki
[SOURCES]
- https://medium.com/@mweststrate
- https://github.com/mobxjs/mobx-utils
- https://github.com/mobxjs/awesome-mobx <- HUGE collection of everything-awesome-mobx
- https://alexhisen.gitbooks.io/mobx-recipes/content/ <- few nice hints of what and what not in MobX
Observables - any value that might be mutated and serve might serve for computed values as a state
Computed values - any value that can be computed by using a function that purely operates on other observable values (NO SIDE EFFECTS)
Reactions - A reaction is a bit similar to a computed value, but instead of producing a new value it produces a side effect
Actions - Actions are the primary means to modify the state. Actions are not a reaction to state changes but take sources of change
Use MobX instead. Now React is truly “just the view” :). MobX now manages both local component state and state in stores.
Like so:
@observer class Select extends React.Component {
@observable selection = null; /* MobX managed instance state */
constructor(props, context) {
super(props, context)
this.selection = props.values[0]
}
onSelect(value) {
this.selection = value
this.fireOnSelect()
}
fireOnSelect() {
if (typeof this.props.onSelect === "function")
this.props.onSelect(this.selection) /* solved! */
}MobX effectively turns your components into small stores
For nice collection of utils check here: https://github.com/mobxjs/mobx-utils
fromPromise - “fromPromise” takes a thennable and returns an object with the properties value, state and reason. These properties are all observable and will update whenever the original promise moves to a different state. This makes it trivial to keep your UI up to date with the progress of a promise.
import {observer} from "mobx-react";
import {fromPromise} from "mobx-utils";
const Profile = observer(({ profile }) => {
switch(profile.state) {
case "pending": return <div>Loading...</div>
case "rejected": return <div>Failed to fetch profile: {profile.reason}</div>
case "fulfilled": return <div>Gotcha: {profile.value.displayName}</div>
}
})
const profileObservable = fromPromise(fetch("http://someurl/myProfile"))
React.render(<Profile profile={profileObservable} />, document.body)