0

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) // 
  })
});
Raymundus
  • 2,173
  • 1
  • 20
  • 35

1 Answers1

0

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

jdobry
  • 1,041
  • 6
  • 17
  • It looks like that should do it, but somehow I still cant get it to work... – Raymundus Aug 23 '16 at 18:48
  • Do you think you could reproduce your issue in a plunker? – jdobry Aug 23 '16 at 20:20
  • Yes, that is the Plunker as added in my question above. Link [here](https://plnkr.co/edit/fU1vbQ?p=preview) – Raymundus Aug 23 '16 at 21:04
  • It looks like replacement does work indeed for basic properties, as in the tests [here](https://github.com/js-data/js-data/blob/8f4ca8ce16953c5f4e6fbe40b70cf9efbf631f7d/test/both/datastore/sync_methods/inject.test.js#L335), but if there is a non-primitive, like the object in my case, the default mixin behavior still takes place, adding missing properties, overwriting existing properties, but not removing any old properties. Hope to get a better solution than setting the object to null, saving, and then setting the right properties and save again. Sidemark: I really REALLY love your work Jason! – Raymundus Aug 27 '16 at 12:19
  • One issue is that `undefined` cannot be serialized to JSON, so what you really need is `tree.apples = {1: 'one', 2: null}`. – jdobry Aug 29 '16 at 14:52
  • That works but that still doesn't remove my second apple key (2). Wouldn't it be more logical behavior for a replace if it would totally replace the entire object (the tree in my example)? – Raymundus Aug 29 '16 at 15:01