Skip to content

findAll() returns array and breaks model.fetch() #231

@heeplr

Description

@heeplr

findAll() at https://github.com/jeromegn/Backbone.localStorage/blob/master/src/sync.js#L34 returns an array which is not taken care for.

When using a model with defaults set, fetch() puts the array into the model attributes. This has multiple implications.

this:

export const Config = Model.extend({
    localStorage: new LocalStorage('Config'),
    defaults: {
        foo: 'bar',
    }
})

const config = new Config()
config.set("foo":"baz")
config.save()
config.fetch()

results in this

>> model.attributes
{
  "0": {
    "foo": "baz",
    "id": "b65b72ba-980f-30f5-dfc3-ae4bfb6dfb94"
  },
  "foo": "bar",
}

Since there is never an id, more arrays get added during the life of the model.

I think a possible fix could be to choose the first element returned by findAll():

try {
    switch (method) {
      case 'read':
-        resp = (0, _underscore.isUndefined)(model.id) ? store.findAll() : store.find(model);
+        resp = (0, _underscore.isUndefined)(model.id) ? store.findAll()[0] : store.find(model);
        break;
      case 'create':
   

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions