-
Notifications
You must be signed in to change notification settings - Fork 4
Using the store
The store can be initialised without any parameters, or it can receive a previously serialised store. To serialise a store, the toJS method should be used:
const storeA = new Store();
storeA.add({firstName: 'John', 'person');
const data = storeA.toJS();
const storeA = new Store(data);
console.log(storeA.length); // 1Models can be added to a store in five ways:
- Using the
syncmethod and passing the raw JSON API response - As an existing model instance:
store.add(modelInstance); - As an array of existing model instances:
store.add([modelInstanceA, modelInstanceB]); - As an plain object and a model type:
store.add(plainObject, modelType); - As an array of plain objects and a model type:
store.add([plainObjectA, plainObjectB], modelType);
The returned value will be a model instance or an array of model instances.
Note: When adding an array of plain JS objects, all of them need to be of the same type.
This can be done in two ways:
// The collection will expose properties that have same names as the registered model types.
console.log(collection.person); // An array of models
console.log(collection.findAll('person')); // An array of modelsconsole.log(collection.find('person', 1));console.log(collection.find('person'));Note: If there are multiple models, it will most likely return the one that was added first, but the order is not guaranteed.
// Removing an exact model
collection.remove('person', 1);
// Remove all models of a certain type
collection.removeAll('person');
// Empty the collection
collection.reset();A model can be removed from the local store and from the API using the destroy method
Existing properties on models can be updated with normal property assignments. There are also three methods that can be used: assign, assignRef and update:
const john = collection.add({firstName: 'John', lastName: 'Doe'}, 'person');
const jane = collection.add({firstName: 'Jane', lastName: 'Doe'}, 'person');
// Should be used only for existing properties
john.lastName = 'Smith';
// Can be used for existing and new properties
john.assign('age', 42);
// Assign a dynamic reference to a model
john.assignRef('spouse', jane);
// Update multiple values
john.update({lastName: 'Williams', age: 25, spouse: null, city: 'San Francisco'});To save the changes to the API, you can use the record save method.
Note: Direct assignment should not be used for new properties because the added property won't be observable (this is a MobX limitation).
For specifics about the exact parameters that can be used with the mentioned methods, check out the Store API reference.