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
.
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.
store
(Store): The store instance to snapshot.
(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.
store
(Store): The store instance to apply state to.state
(any): The state.
(undefined)
The snapshot.$serializer
symbol specifies a custom store method that is used
in place of the state
property when creating a snapshot.
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
.
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