liveBook · Manning

MobX action

As explained in Building User-Friendly DSLs

A MobX action is a function or annotation that identifies an operation allowed to modify observable state.

A MobX action marks code that changes observable state. Wrap a state-changing function with action(...) so updates occur in code MobX permits to mutate observable values. section 5.1.4 section 7.1

Use actions at the boundary where an event or asynchronous callback changes state. In a reactive editor, clicking a value changes editState.inEdit; after editState is observable, an observing component can react to that change. section 5.1.4 section 5.1.4

Common action placements include:

  • A React event handler that starts editing by setting an observable inEdit property. section 5.1.4
  • A DOM mousedown listener that clears selection.selected when the click is outside a selectable element. section 6.2.2
  • A fetch promise callback that stores received JSON in state.ast. section 7.1

Marking a click handler

Import action from mobx and wrap the callback assigned to onClick. The callback can then set editState.inEdit = true; an observer-wrapped TextValue renders an input when that property is true. section 5.1.4 section 5.1.4

import { action, observable } from "mobx"       #1

const apiUrl = "http://localhost:8080/contents" 

fetch(apiUrl) 
    .then((response) => response.json()) 
    .then(action((json) => {       #2
        state.ast = json 
    }))          #3

This callback receives fetched JSON and assigns it to the observable ast property inside action(...), allowing the app to render state loaded from the backend. section 7.1

How Building User-Friendly DSLs covers it

How deep it goes
Demonstrates action(...) wrappers in focused handlers but does not describe MobX internals beyond permitted observable-state changes.
Examples
Uses click-to-edit fields, outside-click deselection, and a fetched Rental AST assigned to state.ast.
What it assumes
Assumes React components, JavaScript callbacks, DOM events, and observable state while showing the action wrapper directly.
What you can do after
Apply it via MobX by wrapping callbacks that assign to observable properties.
How it connects
Connects actions to observable state, observer components, React event handlers, DOM events, fetch, and asynchronous JSON loading.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.