How to make JSData save an instance property to localStorage

119 Views Asked by At

How can I make JSData update a modified object that is saved to localStorage?

The code below saves a Tree object with two apples saved to it in a container object. Now updating that container and saving it 'mixes in to the existing instances' as stated in the docs here.

Q: How can I prevent this mixin behavior so the object contains just one apple after saving?

Plunker

var adapter = new DSLocalStorageAdapter();
var store = new JSData.DS();
store.registerAdapter('localstorage', adapter, { default: true });

var Tree = store.defineResource('tree');

Tree.create({
  id: 1,
  apples: {1: 'one', 2: 'two'}
}).then(function(tree){
  tree.apples = {1: 'one'}
  tree.DSSave().then(function(tree){
    console.log(tree.apples) // 
  })
});
1

There are 1 best solutions below

6
On

You're looking for the onConflict option, which defaults to "merge".

This ought to do it:

tree.apples = {1: 'one', 2: null};
tree.DSSave({ onConflict: 'replace' })
  .then(function (tree){
    console.log(tree.apples);
  });

2.x: http://www.js-data.io/v2.9/docs/dsdefaults#onconflict

3.x: http://api.js-data.io/js-data/latest/Collection.html#onConflict