ember.jsember-data

ember json api camelcase/model attributes undefined


I am using the older Ember 'JSONSerializer' because of the json format being returned by the API;

[
  {
    "userId": 1,
    "id": 1,
    "title": "quidem molestiae enim"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "sunt qui excepturi placeat culpa"
  },
.....
]

The model requires attributes with dashes so I have created an Application Serializer

import JSONSerializer from '@ember-data/serializer/json';
import { dasherize } from '@ember/string';

export default class ApplicationSerializer extends JSONSerializer {
   keyForAttribute(attr) {
     return dasherize(attr)
  }
}

Album Model

import Model, { attr } from '@ember-data/model';

export default class AlbumModel extends Model {
  @attr userId;
  @attr title;
}

But the model attributes are still undefined

Album Template

<h1>album</h1>
  {{#each model as |album|}}
  <li>
  {{album.id}}
  {{album.userId}}
  {{album.title}}
</li>
  {{/each}}

ember-cli: 4.0.1 node: 12.10.0

enter image description here


Solution

  • keyForAttribute specifies the format of the keys in your response payload. By default Ember looks for dasherized keys--in your case, your payload is formatted in camelcase, so you'd want to look for camelized keys. To fix, just override keyForAttribute and return key without modification:

    keyForAttribute(key) {
      return key;
    }