Skip to content

Latest commit

 

History

History
140 lines (94 loc) · 3.09 KB

snapshot.md

File metadata and controls

140 lines (94 loc) · 3.09 KB

megalith.snapshot

Create a state snapshot from a tree of store objects.

The state property on a store instance returns all of its state, but doesn't include child stores. If you have a nested tree of stores you can use snapshot.create to get the complete state tree.

Likewise, you can apply a state tree to stores using snapshot.apply.

Functions

Symbols


Functions

Returns a store's state, along with the state of all children stores.

If a store implements a [$serializer] method, the return value of that method will be used in place of the store's state.

Arguments
  1. store (Store): The store instance to snapshot.
Returns

(any): The complete state tree, including collapsed child stores.


Set a store's state, and the state of all children stores.

If the store implements a [$deserializer] method, the return value of that will be used for the replacement state.

Arguments
  1. store (Store): The store instance to apply state to.
  2. state (any): The state.
Returns

(undefined)


Symbols

The snapshot.$serializer symbol specifies a custom store method that is used in place of the state property when creating a snapshot.

Example
import { Store, snapshot } from 'megalith';

class App extends Store {
  initialState = {
    createDate: new Date(),
  };

  [snapshot.$serializer]() {
    return {
      ...this.state,
      createDate: this.createDate.toJSON(),
    };
  }
}

const app = new App();
snapshot.create(app); // => { createDate: '1985-10-25T01:21:27.051Z' }

The snapshot.$deserializer symbol specifies a custom store method that is used to sanitize and deserialize incoming state data when snapshot.apply is called.

The method must return an object that has the same shape as the store's initialState.

Example
import { Store, snapshot } from 'megalith';

class App extends Store {
  initialState = {
    createDate: new Date(),
  };

  [snapshot.$deserializer](state) {
    return {
      ...state,
      createDate: parseDate(state.createDate),
    };
  }
}

const app = new App();
snapshot.apply(app, {
  createDate: '1985-10-25T01:21:27.051Z',
});
app.createDate.getFullYear(); // => 1985



Documentation