Vinu Prasad
Vinu Prasad

Reputation: 968

Ember data store handling array of objects

I'm new to ember and exploring its capabilities by building a small module. I came across a scenario where I need to update the ember model content synchronously. The ember-data model contains an array of objects as contents.

I was hoping to perform a few tasks as follows

Doing these should automatically sync the data bindings/computed props

My data model after a peekAll call contains 10 records(shown below) on which I need to perform the above operations.

My model is as shown below

export default Model.extend({
  testId: attr('number'),
  name: attr('string')
});

enter image description here

What is the right approach to update the content record? Could someone please suggest how to proceed?

Upvotes: 0

Views: 337

Answers (1)

jrjohnson
jrjohnson

Reputation: 2459

This looks to me like the results of running something like let arr = await store.findAll('test-model'), is that correct? This is probably a PromiseArray and you can access the data as a Javascript Array by calling arr.slice() on it. This will let you do normal array operations, though performing a content re-order doesn't really make much sense in this scenario. I assume you were using it as an example.

For adding and removing records without a network call you can do that by going back to the store and this is what is covered in the docs, you don't need to act on this Object you're looking at.

Adding a new record:

let testModel = store.createRecord('test-model', {
  name: 'Lorem ipsum'
});

testModel.save(); //until you do this no network data will be sent

Removing a record:

let testModel = store.peekRecord('testModel', 1); //to get a record with ID of 1
testModel.deleteRecord();
testModel.save(); //until you run save no network is sent

Once you've taken action like this on the store the data structure you posted above may be updated to contain the new data depending on how you accessed it originally. You can also re-fetch data from the store which will now know about your adding a deleting of models (even though you haven't saved it back to the server yet)

If you haven't saved yet and you re-do a peekRecord you'll need to filter out any deleted records from the results.

let undeletedModels = this.store.peekAll('test-model').filter(m => !m.isDeleted);

Upvotes: 2

Related Questions