- philosophy
- overview
- observables
- reactions: autorun
- derived values: computed
- actions
Making things observable
- observable.box
- observable.object
import { recordPatches } from "mobx-state-tree" | |
const runningActions = new Map() | |
export function atomicAsyncPatch(call, next) { | |
switch (call.type) { | |
case "action": | |
return atomic(call, next) | |
case "process_spawn": { | |
const recorder = recordPatches(call.tree) |
import produce from "immer" | |
const nextState = produce(currentState, draft => { | |
// empty function | |
}) | |
console.log(nextState === currentState) // true |
import produce from "immer" | |
const todos = [ /* 2 todo objects in here */ ] | |
const nextTodos = produce(todos, draft => { | |
draft.push({ text: "learn immer", done: true }) | |
draft[1].done = true | |
}) | |
// old state is unmodified |
// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js | |
const byId = (state, action) => { | |
switch (action.type) { | |
case RECEIVE_PRODUCTS: | |
return { | |
...state, | |
...action.products.reduce((obj, product) => { | |
obj[product.id] = product | |
return obj | |
}, {}) |
// ImmutableJS | |
const newMap = map.updateIn(['inMap', 'inList'], list => list.push(4)) | |
// Immer | |
draft.inMap.inList.push(4) |
const byId = produce((draft, action) => { | |
switch (action.type) { | |
case RECEIVE_PRODUCTS: | |
action.products.forEach(product => { | |
draft[product.id] = product | |
}) | |
break | |
} | |
}) |
const CityView = observer(({ city }) => ( | |
<li> | |
City: {city.location} - Temperature in ℃: {city.temperature || 'Loading'} | |
</li> | |
)) |
import { when } from "mobx" | |
async() => { | |
await when(() => user.loggedOut) | |
alert("You have been successfully logged out!") | |
} |
Making things observable
import { decorate, observable, flow } from "mobx" | |
/** | |
with decorator syntax enabled | |
*/ | |
class City { | |
@observable location | |
@observable temperature | |
@action.bound |