Skip to content

MobX and React ​

Make generated models observable and use them in React components.

The mobx extension makes validators and SDK operations observable. asGenObservable makes the fields of a generated model observable.

  • Annotate your class's own fields, getters and actions with normal MobX annotations.
  • Nested generated models are initialized recursively and keep their identity.

Create src/payment-editor.model.ts:

ts
import { model, type IModel, type ModelInit } from '@exprtlabs/golem/model';
import { asGenObservable } from '@exprtlabs/golem-openapi-ts/mobx';
import { getValidator } from '@exprtlabs/golem/validation';
import { action, computed } from 'mobx';
import type { TMoney } from '../sdk/index.js';

export type TPaymentEditor = IModel<{ money: TMoney; note: string }>;

export class PaymentEditor extends model<TPaymentEditor>() {
  public constructor(values: Partial<ModelInit<TPaymentEditor>> = {}) {
    super({ money: { amount: '0.00', currency: 'USD' }, note: '', ...values });
    asGenObservable(this, { summary: computed, setAmount: action, setCurrency: action, setNote: action });
    getValidator(this).extend({ note: value => value.length <= 140 || 'Keep the note within 140 characters' });
    // Readable messages for the generated pattern checks of the nested money object.
    getValidator(this).messages([
      { path: ['money', 'amount'], code: 'pattern', message: 'Enter an amount like 12.50' },
      { path: ['money', 'currency'], code: 'pattern', message: 'Use a three-letter currency code like USD' },
    ]);
  }

  public get summary(): string {
    return `${this.money.amount} ${this.money.currency}${this.note ? `: ${this.note}` : ''}`;
  }

  public setAmount(amount: string): void {
    this.money.amount = amount; // The nested money model is observable too.
  }

  public setCurrency(currency: string): void {
    this.money.currency = currency.toUpperCase();
  }

  public setNote(note: string): void {
    this.note = note;
  }
}

MobX changes observability only. Construction, fromWireFormat / toWireFormat, parse / stringify and validation keep their normal behavior.

Enable MobX ​

Install MobX and @exprtlabs/golem-openapi-ts in the application. Your class constructors and the generated files import them at run time, so @exprtlabs/golem-openapi-ts belongs in dependencies, not in devDependencies:

sh
npm install mobx @exprtlabs/golem-openapi-ts

A React app also needs mobx-react-lite, which provides observer (Use it in React):

sh
npm install mobx-react-lite

Turn on the extension in the openapi-ts block and regenerate:

yaml
version: 1
validation: true
openapi-ts:
  sdks:
    - input: ../server/api/openapi.yaml
      output: sdk
      name: Payments
      mode: golem
  extensions:
    mobx: {}
model: {}

extensions: { mobx: {} } makes the validators of your models observable. The example also sets validation: true. Validation is independent of MobX (Validate models). A project with models and no SDK writes the block with only extensions (MobX extension).

An SDK in a block with the extension also gains observable operation loading (Call operations). Such an SDK needs mode: golem on its SDK job and a model block in the same file, as the example sets. A standalone SDK carries its own copy of the runtime, and that copy has no MobX support, so generation stops with OPENAPI_MOBX_NEEDS_GOLEM_MODE. Set mode: golem, or remove mobx from extensions (SDK modes).

  • An SDK has no model classes in either mode, so the data it returns is plain and not observable.
  • For observable data, declare your own model over the SDK type, such as IModel<Charge>, and call asGenObservable in its constructor.

Initialize your class ​

Call asGenObservable(this, annotations) once in your constructor, after super(values) and after your own field initializers. Later calls such as getValidator(this).extend() are fine. A second asGenObservable call on the same instance throws.

  • Extra annotations are optional: asGenObservable(this, { label: computed, toggle: action }).
  • Annotate writable state with observable, derived getters with computed and state-changing methods with action.
  • Use observable.ref, observable.shallow, observable.struct, or false when a field should not be deeply observable.
  • An empty class Payment extends model<TPayment>() {} is not observable until its constructor calls asGenObservable(this). This holds for a model over an SDK type too.

Observe a model ​

autorun runs once immediately and again when a value it reads changes. summary is the computed getter in the class above.

src/summary.ts:

ts
export function observeSummary(editor: PaymentEditor, report: (summary: string) => void): () => void {
  return autorun(() => report(editor.summary)); // Runs again when the amount, currency or note changes.
}

Dispose the reaction when the observation is no longer needed.

Nested models ​

When an observable generated model contains another generated model or a plain object, asGenObservable walks nested values through arrays, records, maps and sets.

The golem.yaml above generates the SDK into sdk/ from ../server/api/openapi.yaml. A model that uses SDK types is observable together with its nested SDK values. In src/payment-editor.model.ts, setAmount edits the nested money object:

ts
public setAmount(amount: string): void {
  this.money.amount = amount; // The nested money model is observable too.
}

Calling setAmount('12.50') changes money.amount, and the reaction above reports the new summary.

  • money has the SDK type TMoney, a plain object type.
  • asGenObservable makes that nested object observable, so it needs no manual MobX call.
  • setAmount is an action. The reaction runs after it updates money.amount.

Unions and your classes ​

Put annotations on your class, after super. When a union field holds one of your classes, construct it with new YourClass(…). Generated union conversion builds only generated classes.

Without the extension, generated files import no MobX.

Use it in React ​

A React component imports a generated model or client like any other module. Wrap a component that reads observable fields in observer from mobx-react-lite. It re-renders when a field it read changes. Operation loading is observable too (Call operations).

The amount field in src/App.tsx, which wraps every field of the form the same way:

tsx
const AmountField = observer(function AmountField({ editor }: { editor: PaymentEditor }) {
  const error = getValidator(editor).errors['/money/amount']?.[0]; // Re-renders when the validation errors change.
  return (
    <label className="field">
      <span>Amount</span>
      <input
        aria-invalid={error ? true : undefined}
        inputMode="decimal"
        name="amount"
        onChange={event => editor.setAmount(event.currentTarget.value)}
        type="text"
        value={editor.money.amount} // Re-renders when the amount changes.
      />
      {error && <span className="field-error">{error}</span>}
    </label>
  );
});

getValidator reads the editor's validation issues (Validate models) for the field to render. The field calls an action method, setAmount, on change.

  • Import getValidator from @exprtlabs/golem/validation. When the mobx extension is on and validation is true, the validator it returns is already observable, so observer re-renders when its issues change.
  • Import it from @exprtlabs/golem-openapi-ts/mobx-validation when a model is generated without both settings and a component must still re-render on its issues. It returns the same validator for that instance, made observable.

Bind a text input to a number field ​

A text input holds a string. The amount field above holds text, so its input needs no draft. The instalments field holds a number, so its input keeps a draft string. The model has the number and an action:

ts
import { model, type IModel, type ModelInit } from '@exprtlabs/golem/model';
import { asGenObservable } from '@exprtlabs/golem-openapi-ts/mobx';
import type { Integer, Minimum } from '@exprtlabs/golem/tags';
import { action } from 'mobx';

// The number of instalments that a payment splits into.
export type TSplitEditor = IModel<{ parts: number & Integer & Minimum<1> }>;

export class SplitEditor extends model<TSplitEditor>() {
  public constructor(values: Partial<ModelInit<TSplitEditor>> = {}) {
    super({ parts: 1, ...values });
    asGenObservable(this, { setParts: action });
  }

  public setParts(parts: number): void {
    this.parts = parts;
  }
}

The store converts the draft and calls the action only when the draft converts:

ts
// Converts the text of the input to a number. A half-typed `3.`, an empty text or 0 does not convert.
function toParts(draft: string): number | undefined {
  const parts = /^[0-9]+$/.test(draft) ? Number(draft) : NaN;
  return Number.isSafeInteger(parts) && parts >= 1 ? parts : undefined; // The model field has Minimum<1>.
}
ts
public setPartsDraft(draft: string): void {
  this.partsDraft = draft; // The input always shows the draft.
  const parts = toParts(draft);
  if (parts !== undefined) this.split.setParts(parts); // Only a draft that converts reaches the model.
}

public get partsDraftError(): string | undefined {
  return toParts(this.partsDraft) === undefined ? 'Enter a whole number like 3' : undefined;
}

In makeObservable, mark partsDraft observable, partsDraftError computed and setPartsDraft an action.

The input shows the draft, never the number. It also shows the message for a draft that does not convert:

tsx
const PartsField = observer(function PartsField({ store }: { store: PaymentStore }) {
  const error = store.partsDraftError ?? getValidator(store.split).errors['/parts']?.[0]; // The draft check first, then the tags of the number.
  return (
    <label className="field">
      <span>Instalments</span>
      <input
        aria-invalid={error ? true : undefined}
        inputMode="numeric"
        name="parts"
        onChange={event => store.setPartsDraft(event.currentTarget.value)}
        type="text"
        value={store.partsDraft} // The draft, never the number.
      />
      {error && <span className="field-error">{error}</span>}
    </label>
  );
});

Show field errors ​

Validate the editor. The errors then appear in the validator that each field reads:

ts
const valid = await getValidator(this.editor).validate({ failFast: false });
if (!valid) {
  runInAction(() => { this.saveState = 'idle'; });
  return false;
}
  • validate({ failFast: false }) stores every error. A change to a field does not clear its old error, so validate again.
  • validator.error('note') returns the first message of a field. The other members are in Stored validation state.
  • The tags of the number field check the number. A negative amount fails Minimum<0>. The text of the draft is your check.

Full example: examples/payments runs this editor against a local demo server.