DS.store - Fetching and Handling data

Can someone please elaborate on how to use the store with an example ? As in, how to put a model into the store, how to retrieve it using an ID ? How to define the attr in the model? In short, how to make use of the DS.store for data handling ?

I’d recommend you read the guides carefully, they actually explain this stuff pretty well and even have some nifty diagrams that show the layers of data flow (app > store > adapter > server), etc.

How to define the attr in the model?

This page should have everything pretty well covered with a number of examples (even custom transforms!)

how to retrieve it using an id?

You can either use peekRecord(<type>, <id>) to get a model that you know is already in the store or you can use findRecord(<type>, <id>) to do a cached fetch from the server (meaning if the record is in the store already it returns it immediately and then refreshes it from the server, if not it fetches it from the server and returns it). Check out this page of the guides.

how to put a model into the store

After you define the model (and customize the adapter, if necessary) you can get models into the store in several ways:

  • create a new record on the front-end, this is usually done with intent to save (POST) it to the server. Use store.createRecordto create it in the store, record.save to do the POST.
  • fetch a record from the server using findAll/findRecord/query. This fetches data dnd serializes it into a store model
  • fetch (or create) raw data and use store.push/pushPayload to shove it into the store. This method is less common.

Ember Data can get pretty complex but using the basics are pretty easy. Just keep a few things in mind as you go:

  • ember data gets you a lot and is the de facto way of fetching/caching data, but it is by no means the only way and it is not required to use ember
  • the store is both a caching layer for records and the interface by which you fetch them
  • good design patters generally mean keeping models flat (no nested attributes, use relationships instead), clean (devoid of business logic, use computed properties when appropriate but you should probably avoid injecting services or mutating state in a model), etc.
  • depending on your backend data source you may need to customize the adapter/serializer layer, this can get complex but it can really pay off once you get it nailed down
  • if you don’t have a backend already (or even if you do) you can do prototype/mock development with ember-cli-mirage until you’re ready to implement/integrate your backend.

And of course if you have any specific questions feel free to post them here.

1 Like

Thanks a lot ! Will try them.