Constructor

FormStore Constructor takes two Object-type arguments - options (required) and data (optional), i.e.:

new FormStore(options, data);

Options (required)

Data (optional)

If you provide a data object, it will be used as the 'reference/from-server' data set (known internally as dataServer) and upon a successful save(), this object will be updated in place with the updated data.

If you don't provide a data object as the second argument to the constructor, you must provide a server.get method and until model.refresh() is called, model.status.isReady will be false (the form should not allow user input while the model is in this state).

IMPORTANT: Currently the data object (whether provided to constructor or returned by server.get/set/create) must be flat (i.e. model.data.addressLine1, not model.data.address.line1. Change-tracking and auto-save will not work correctly with nested objects. However, with some fairly simple improvements in reset(), status(), getValue(), and startEditing(), FormStore could support full saves with save({ saveAll: true }) and provide facilities for validation error tracking in nested data objects.

Server-returned updated data

The objects returned by server.set and server.create can include a data property. Its contents will be merged into the FormStore instance data (and savedData), overwriting existing values there.

IMPORTANT: Any data properties returned by server.set/create must already exist in the FormStore instance or they will not be observed by MobX.

Computed values

Starting with mobx-form-store v1.2.0, you can now maintain some properties in data as read-only computeds and their changes will be tracked and their values saved just like regular properties. These computeds can be either in the data object provided to the constructor or returned by server.get or they can be added (or converted from static values) in the afterRefresh callback:

import { extendObservable } from "mobx";

new FormStore({
  ...
  afterRefresh: async (store) => {
    // define a computed that composes name from firstName and lastName
    delete store.data.name; // required if re-defining existing property with MobX 4+
    extendObservable(store.data, {
      get name() {
        return (store.data.firstName || store.data.lastName) && `${store.data.firstName || ''} ${store.data.lastName || ''}`.trim();
      },
    });
  },
});

Last updated